Java正则表达式匹配计数 [英] java regex match count

查看:290
本文介绍了Java正则表达式匹配计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  HelloxxxHelloxxxHello 


我编译一个模式来寻找'Hello' c $ c> Pattern pattern = Pattern.compile(Hello);然后,我使用一个输入流来读取文件,并将其转换为一个字符串,以便它可以正确匹配。

一旦匹配器在文件中找到一个匹配项,就表明这一点,但它并不告诉我它找到了多少匹配项;简单的说,它在String中找到了一个匹配。

因此,由于字符串相对较短,我使用的缓冲区是200字节,所以应该找到三个匹配。然而,它只是说匹配,并没有提供我有多少匹配计数。

什么是最简单的方法来计算匹配的数量发生在字符串内。我已经尝试了各种for循环,并使用matcher.groupCount(),但我得到了无处不在的快速。

解决方案

matcher.find()找不到全部匹配,只有下一个匹配。 b $ b

您必须执行以下操作:

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

顺便说一句, matcher.groupCount()

$ hr
$ b

完整示例

  import java.util.regex。*; 
$ b $ class Test {
public static void main(String [] args){
String hello =HelloxxxHelloxxxHello;
Pattern pattern = Pattern.compile(Hello);
Matcher匹配器= pattern.matcher(hello);

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

System.out.println(count); //打印3
}
}


Let's say I have a file, and the file contains this:

HelloxxxHelloxxxHello

I compile a pattern to look for 'Hello'

Pattern pattern = Pattern.compile("Hello");

Then I use an inputstream to read in the file and convert it into a String so that it can be regexed.

Once the matcher finds a match in the file, it indicates this, but it doesn't tell me how many matches it found; simply that it found a match within the String.

So, as the string is relatively short, and the buffer I'm using is 200 bytes, it should find three matches. However, it just simply says match, and doesn't provide me with a count of how many matches there were.

What's the easiest way of counting the number of matches that occured within the String. I've tried various for loops and using the matcher.groupCount() but I'm getting nowhere fast.

解决方案

matcher.find() does not find all matches, only the next match.

You'll have to do the following:

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

Btw, matcher.groupCount() is something completely different.


Complete example:

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
    }
}

这篇关于Java正则表达式匹配计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆