java正则表达式匹配计数

Ton*_*ony 87 java regex matcher find

假设我有一个文件,该文件包含:

HelloxxxHelloxxxHello
Run Code Online (Sandbox Code Playgroud)

我编译一个模式来寻找'你好'

Pattern pattern = Pattern.compile("Hello");
Run Code Online (Sandbox Code Playgroud)

然后我使用输入流来读取文件并将其转换为String,以便可以对其进行重新编码.

一旦匹配器在文件中找到匹配项,它就表明了这一点,但它没有告诉我它找到了多少匹配项; 只是它在String中找到了匹配项.

因此,由于字符串相对较短,并且我使用的缓冲区是200字节,因此它应该找到三个匹配项.但是,它只是简单地说匹配,并没有向我提供有多少匹配的计数.

计算String中发生的匹配数的最简单方法是什么.我已经尝试了各种for循环并使用matcher.groupCount(),但我无处可去.

aio*_*obe 162

matcher.find()没有找到所有的比赛,只有一场比赛.

你必须做以下事情:

int count = 0;
while (matcher.find())
    count++;
Run Code Online (Sandbox Code Playgroud)

顺便说一句,matcher.groupCount()是完全不同的东西.

完整的例子:

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxxxHelloxxxHello";
        Pattern pattern = Pattern.compile("Hello");
        Matcher matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3
    }
}
Run Code Online (Sandbox Code Playgroud)

处理重叠匹配

当计算上述片段aaaaaa的匹配时,您将获得2.

aaaa
aa
  aa
Run Code Online (Sandbox Code Playgroud)

要获得3个匹配,即此行为:

aaaa
aa
 aa
  aa
Run Code Online (Sandbox Code Playgroud)

您必须在索引中搜索匹配,<start of last match> + 1如下所示:

String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);

int count = 0;
int i = 0;
while (matcher.find(i)) {
    count++;
    i = matcher.start() + 1;
}

System.out.println(count);    // prints 3
Run Code Online (Sandbox Code Playgroud)


小智 15

这适用于非不相交的匹配:

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);
}
Run Code Online (Sandbox Code Playgroud)


小智 7

从 Java 9 开始,您可以使用提供的流 Matcher.results()

long matches = matcher.results().count();
Run Code Online (Sandbox Code Playgroud)