How to count the number of times a regex captures a group ?
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++;
精彩评论