我有一个字符串,例如:
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 能够正确计算这两种情况?
最佳答案
您可以将模式匹配与使用 word-boundaries 的正则表达式 '\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
等执行相同的操作。
关于java - 正则表达式匹配由空格分隔的数字字符串中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32982567/