java - 正则表达式提取范围内的数字

标签 java regex

我想从给定的字符串中提取 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

预期输出应忽略字符串中的 202122。现在,22 在显示中被拆分为 22,这不是预期的。

最佳答案

添加单词边界:

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/

相关文章:

java - 如何计算运行时选择的类型 "object"

Java 编译速度 vs Scala 编译速度

Javascript 正则表达式对象无法识别 {n,m}

regex - [A-Z] 是什么意思 [A-Za-z]?

regex - ARGS , ARGS_NAMES 在 mod_security crs 中实际上是什么意思?

c# - 检测正则表达式后的单词

java - 在 Couchbase 中调用删除文档(带分页)时的 Spring Data "TimeoutException"

java发布表单并在重定向后获取响应 header

java - 从 Java 应用程序查找 Windows 服务的状态?

regex - 如何在vim中折叠所有出现的正则表达式?