假设我有一个包含以下内容的字符串:
HelloxxxHelloxxxHello
我编译了一个模式来查找“Hello”
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher("HelloxxxHelloxxxHello");
它应该会找到三个匹配项。我如何才能计算出有多少个匹配项?
我尝试了各种循环和使用matcher.groupCount()
,但都不起作用。
发布于 2016-05-01 03:32:20
这应该适用于可能重叠的匹配:
public static void main(String[] args) {
String input = "aaaaaaaa";
String regex = "aa";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int from = 0;
int count = 0;
while(matcher.find(from)) {
count++;
from = matcher.start() + 1;
}
System.out.println(count);
}
发布于 2019-11-20 12:29:00
在Java9中,您可以使用Matcher.results()
提供的流
long matches = matcher.results().count();
发布于 2018-08-16 16:53:44
如果你想使用Java8Streams,并且对while
循环敏感,你可以尝试这样做:
public static int countPattern(String references, Pattern referencePattern) {
Matcher matcher = referencePattern.matcher(references);
return Stream.iterate(0, i -> i + 1)
.filter(i -> !matcher.find())
.findFirst()
.get();
}
免责声明:这只适用于不相交的匹配。
示例:
public static void main(String[] args) throws ParseException {
Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
System.out.println(countPattern("[ ]", referencePattern));
}
这将打印出来:
2
0
1
0
这是一个针对流的不相交匹配的解决方案:
public static int countPattern(String references, Pattern referencePattern) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
new Iterator<Integer>() {
Matcher matcher = referencePattern.matcher(references);
int from = 0;
@Override
public boolean hasNext() {
return matcher.find(from);
}
@Override
public Integer next() {
from = matcher.start() + 1;
return 1;
}
},
Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}
https://stackoverflow.com/questions/7378451
复制相似问题