从字符串中分隔数字

mut*_*mar 1 java

我想得到给定字符串的数字,我使用下面的代码

String sample = "7011WD";
    String output = "";
    for (int index = 0; index < sample.length(); index++)
    {
        if (Character.isDigit(sample.charAt(index)))
        {
            char aChar = sample.charAt(index);
            output = output + aChar;
        }
    }

    System.out.println("output :" + output);
Run Code Online (Sandbox Code Playgroud)

结果是: 输出:7011

有没有简单的方法来获得输出?

NIN*_*OOP 6

有没有简单的方法来获得输出

可能是你可以使用正则表达式\\D+(D任何不是数字,+意味着一个或多个出现),然后String#replaceAll()所有非数字与空字符串:

String sample = "7011WD";
String output = sample.replaceAll("\\D+","");
Run Code Online (Sandbox Code Playgroud)

虽然记住,使用正则表达式根本就没有效率.此外,此正则表达式也将删除小数点!

您需要使用整数#parseInt函数(输出)龙#parseLong(输出),以获得原始intlong分别.


您也可以使用Google的Guava CharMatcher.指定使用范围INRANGE() ,并从该范围中的序列作为返回字符String使用retainFrom() .