我想从给定的字符串中提取 1 到 19 之间的数字。
String n="1 21 16 17 9 8 22 20 10";
Pattern p=Pattern.compile("(1[0-9]|[0-9])");
Matcher m=p.matcher(n);
while(m.find())
System.out.println(n.substring(m.start(),m.end()));
}
我获得的输出:
1
2
1
16
17
9
8
2
2
2
0
10
预期输出应忽略字符串中的 20
、21
、22
。现在,22
在显示中被拆分为 2
和 2
,这不是预期的。
最佳答案
添加单词边界:
String n="1 21 16 17 9 8 22 20 10";
Pattern p=Pattern.compile("\\b(1[0-9]|[0-9])\\b");
Matcher m=p.matcher(n);
while(m.find())
System.out.println(n.substring(m.start(),m.end()));
}
参见demo
关于java - 正则表达式提取范围内的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30050071/