![](/img/trans.png)
[英]Regular Expression to match spaces between numbers and operators but no spaces between numbers
[英]regular expression to match a number on a String of numbers that are separated by spaces
我有一个字符串,例如:
String s = " 10 5 15 55 5 ";
并且我正在尝试使用regExp获取数字的重复次数(在本例中为5),因此我的方法如下:
long repetitions = s.split(" 5").length -1;
但这不起作用,它也匹配55。
如果我在数字的两边都使用空格,则类似:
String s=" 10 10 15 5 ";
long repetitions = s.split(" 10 ").length -1;
它不起作用,它仅计数10个实例中的一个(我有两个)。
所以我的问题是哪个regExp可以正确计算两种情况?
您可以将模式匹配与正则表达式'\\b5\\b'
使用,后者使用单词边界查找不属于“其他内容的5
”:
String s = " 10 5 15 55 5 ";
Pattern p = Pattern.compile("(\\b5\\b)");
Matcher m = p.matcher(s);
int countMatcher = 0;
while (m.find()) { // find the next match
m.group();
countMatcher++; // count it
}
System.out.println("Number of matches: " + countMatcher);
输出值
Number of matches: 2
您可以对10
等等执行相同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.