import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "x(?:(?(1)(?!)|(a))|(?(2)(?!)|(b))|.){0,10}?y(?(1)|(?!))(?(2)|(?!))";
final String string = "Match:\n"
+ "...x12a456b89y... ...x12a456b89y... \n"
+ "...xaabbaabby...\n"
+ "x...a.y.b...y (there are 11 chars between x and y, no match is correct!)\n"
+ "...x..a...b..y...\n"
+ "...x..b...a..y...\n"
+ "...x..a...b..y...a...\n"
+ "...x..a...b..y...b...\n"
+ "...x..a...b..y...y...\n"
+ "...x..a.x.b..y...\n"
+ "...x..a.y.b..y...\n"
+ "...xaabbaabbay...\n"
+ "...x..a...b..y... ...x..a...b..y... (2 matches)\n"
+ "...xaby...xaby... (2 matches)\n\n"
+ "Don't match:\n"
+ "...x..a...b......\n"
+ "...x......b..y...\n"
+ "...x..a......y...\n"
+ "...x..a...b......y...\n"
+ "...x......b..y...a...\n"
+ "...x..a......y...b...\n"
+ "...x..a.y.b......\n"
+ "...x..a.y.b......y...\n"
+ "...x..a.y.b.x....y...\n"
+ ".a.x......b..y...\n"
+ ".b.x..a......y...\n"
+ "x...y...a...b";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
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