package javaapplication1;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
// X{n} , X{n}? and X{n}+ (X exactly n times)
searchREGEX("catcatcatcatcat", "(cat){3}", "(cat){3}?", "(cat){3}+");
searchREGEX("catcatcatcatcat", "[cat]{3}", "[cat]{3}?", "[cat]{3}+");
}
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(String.format("%s: Not found\n", regex));
}
}
}
/*
run:
(cat){3}: Found "catcatcat" from index 0 to 9
(cat){3}?: Found "catcatcat" from index 0 to 9
(cat){3}+: Found "catcatcat" from index 0 to 9
[cat]{3}: Found "cat" from index 0 to 3
[cat]{3}: Found "cat" from index 3 to 6
[cat]{3}: Found "cat" from index 6 to 9
[cat]{3}: Found "cat" from index 9 to 12
[cat]{3}: Found "cat" from index 12 to 15
[cat]{3}?: Found "cat" from index 0 to 3
[cat]{3}?: Found "cat" from index 3 to 6
[cat]{3}?: Found "cat" from index 6 to 9
[cat]{3}?: Found "cat" from index 9 to 12
[cat]{3}?: Found "cat" from index 12 to 15
[cat]{3}+: Found "cat" from index 0 to 3
[cat]{3}+: Found "cat" from index 3 to 6
[cat]{3}+: Found "cat" from index 6 to 9
[cat]{3}+: Found "cat" from index 9 to 12
[cat]{3}+: Found "cat" from index 12 to 15
*/