import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(at){2}";
final String string = "There is nothing to match in this sentence because it doesn't have the repeating pattern. The pattern is the letters \"at\" together, using the parenthesis to group the letters we want to look for, repeated two times.\n"
+ "It will find a match in the following: \"The machine gun went ratat.\"\n"
+ "No match here because of the spaces: \"The machine gun went rat at\"\n"
+ "This will partially match since it is looking for \"at\" twice in a row, but will not match the full repetition since it actually repeats three times: \"The machine gun went ratatat.\" To fix this, we could change the expresion to \"(at){2,}\" which says find the letters \"at\" repeated two or more times.";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html