简体   繁体   English

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

[英]regex to extract number in range

I want to extract numbers from 1 to 19 from the given string. 我想从给定的字符串中提取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()));
}

Output I obtain: 我得到的输出:

 1
 2
 1
 16
 17
 9
 8
 2
 2
 2
 0
10

Expected output should ignore 20 , 21 , 22 from the string. 预期输出应该忽略202122从该字符串。 Right now, instead of that, 22 gets split into 2 and 2 in the display which is not expected. 现在,不是那样,而是在显示屏上将22拆分为22 ,这是不期望的。

Add word boundaries: 添加单词边界:

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()));
}

See demo 观看演示

使用单词边界:

Pattern p=Pattern.compile("\\b(1[0-9]|[0-9])\\b");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM