package javaapplication1;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
// X{n,m} , X{n,m}? and X{n,m}+ (X at least n but not more than m times)
searchREGEX("aaabaa", "a{2,4}", "a{2,4}?", "a{2,4}+");
}
private static void searchREGEX(String input, String... regex_list) {
for (String regex : regex_list) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
boolean found = false;
while (matcher.find()) {
System.out.println(String.format("%s: Found" + " \"%s\" " + "from index %d to %d",
regex, matcher.group(), matcher.start(), matcher.end()));
found = true;
}
System.out.println();
if (!found)
System.out.println("Not found");
}
}
}
/*
run:
a{2,4}: Found "aaa" from index 0 to 3
a{2,4}: Found "aa" from index 4 to 6
a{2,4}?: Found "aa" from index 0 to 2
a{2,4}?: Found "aa" from index 4 to 6
a{2,4}+: Found "aaa" from index 0 to 3
a{2,4}+: Found "aa" from index 4 to 6
*/