import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NonCapturingGroupExample {
public static void main(String args[]) {
String regex = "hello|hi|greetings|(?:good morning)";
String candidate1 = "Java2s say hi to you";
String candidate2 = "Java2s say good morning to you";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(candidate1);
System.out.println("GROUP COUNT:" + matcher.groupCount());
if (matcher.find())
System.out.println("GOT 1:" + candidate1);
matcher.reset();
matcher = pattern.matcher(candidate2);
System.out.println("GROUP COUNT:" + matcher.groupCount());
if (matcher.find())
System.out.println("GOT 2:" + candidate2);
}
}
|