假设我有一个字符串。
String str = "Hello6 9World 2, Nic8e D7ay!";
Matcher match = Pattern.compile("\\d+").matcher(str);
上面的行会给我 6、9、2、8 和 7,这是完美的!
但是如果我的字符串更改为..
String str = "Hello69World 2, Nic8e D7ay!";
请注意,该字符串中 6 和 9 之间的空格已被删除。
如果我运行..
Matcher match = Pattern.compile("\\d+").matcher(str);
它会给我 69、2、8 和 7。
我的要求是仅提取个位数。这里,我需要的是 2, 8, 7,省略 69。
你能帮我改进我的正则表达式吗?谢谢!
最佳答案
对于每个数字,您必须检查它后面或前面是否没有 数字
你可以试试这个:
public static void main(String[] args) {
String str = "Hello69World 2, Nic8e D7ay!";
Pattern p = Pattern.compile("(?<!\\d)\\d(?!\\d)");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group());
}
System.out.println("***********");
str = "Hello6 9World 2, Nic8e D7ay!";
m = p.matcher(str);
while (m.find()) {
System.out.println(m.group());
}
}
操作:
2
8
7
***********
6
9
2
8
7
关于java正则表达式从字符串中提取 'only'个位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48943931/