我有一个字符串:
String s = "12 text var2 14 8v 1";
我只需要从此字符串中获取数字,例如:
12 14 1.
但我不需要这样的词:
var2 and 8v.c
我尝试过这个:
str = str.replaceAll("[^\\d.]", "");`
最佳答案
如果您确实想使用 String.replaceAll
来实现此目的,有一个解决方法:
// | one or more non-digits
// | | followed by one or more digits
// | | | followed by one or more non-digits
// | | | | or the end of the input
// | | | | | replace with single white space
s.replaceAll("\\D+\\d+(\\D+|$)", " ");
输出
12 14 1
但是,这个解决方案很丑陋,并且可能会因不同的输入而崩溃。
我建议您解析正数,并通过迭代输入来收集。
大致如下:
// | word boundary
// | | one or more digits
// | | | word boundary
Pattern p = Pattern.compile("\\b\\d+\\b");
关于Java字符串删除所有非数字字符和单词,如var123,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501753/