开发者

How to count the number of times a regex captures a group ?

开发者 https://www.devze.com 2023-04-12 01:16 出处:网络
I have the regex ([A-Za-z]+) My example text is: jerk jerk jerk jerk jerk jerk jerk jerk jerk jerk I\'m开发者_如何学JAVA trying to find out how many times a group is captured in an example. I wan

I have the regex ([A-Za-z]+)

My example text is:

jerk jerk jerk jerk jerk jerk jerk jerk jerk jerk 

I'm开发者_如何学JAVA trying to find out how many times a group is captured in an example. I want the answer for the example input to be 10.

How would I go implementing this?


You have to specify what you want to match in the regex. What you have will match any alphabetic character. Here you go:

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main( String[] args ) throws IOException //throws exceptions
    {
        String str = "jerk jerk jerk jerk\njerk jerk jerk\njerk jerk\njerk";
        String regex = "jerk";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        int count = 0;
        while(m.find())
            count++;
        System.out.println(count);
    }
}


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号