[英]java regex to extract 'only' the single digit numbers from a string
假设我有一个字符串。
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());
}
}
O / P:
2
8
7
***********
6
9
2
8
7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.