Java如何从字符串中提取数字

x33g5p2x  于2020-12-18 发布在 Java  
字(1.3k)|赞(0)|评价(0)|浏览(841)

有几种方法可以从字符串中提取数字。

使用正则表达式提取数字
使用for语句提取数字
使用流提取号码

最简单的方法是使用正则表达式(Regex)。让我们用示例看一下上面列出的方法。

使用正则表达式提取Integer

以下代码是仅提取Integer作为正则表达式的代码。 replaceAll()将正则表达式和要转换的字符串作为参数传递。

String str = "aaa1234, ^&*2233pp";
String intStr = str.replaceAll("[^0-9]", "");
System.out.println(intStr);
// output: 12342233

"[^0-9]"表示从0到9的非数字字符串。

因此,这""意味着将非数字字符更改为空格()。

以下代码也输出与上面相同的结果。 "^\d"是"[^0-9]"的缩写,具有相同的含义。

String str = "aaa1234, ^&*2233pp";
String intStr = str.replaceAll("[^\\d]", "");
System.out.println(intStr);
// output: 12342233

此方法是最短的代码,因此我们建议使用此方法。

要了解有关正则表达式的更多信息,请参见Java-Regular Expressions(regex)Example。

使用for语句提取数字

以下代码是仅使用for语句提取Integer的代码。

String str = "aaa1234, ^&*2233pp";
String intStr = "";
for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (48 <= ch && ch <= 57) {
        intStr += ch;
    }
}
System.out.println(intStr);
// output: 12342233

48表示ASCII中的数字0,57表示ASCII中的数字9。换句话说,它是仅从字符串中提取0到9之间的数字的代码。

将数字提取到流中

以下代码将数字提取到Stream中。for语句和算法相同。相反,我们没有使用for,而是使用Stream来处理它。

String str = "aaa1234, ^&*2233pp";
IntStream stream = str.chars();
String intStr = stream.filter((ch)-> (48 <= ch && ch <= 57))
        .mapToObj(ch -> (char)ch)
        .map(Object::toString)
        .collect(Collectors.joining());
System.out.println(intStr);
// output: 12342233

相关文章

微信公众号

最新文章

更多