import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?=\\b\\d{8}\\b)(?:(?:9?8?7?6?5?4?3?2?1?0?)|(?:0?1?2?3?4?5?6?7?8?9?))(?<=\\d{8})";
final String string = "This regex is to match Ascending or descending order of 8 digit number\n"
+ "01234567 0 to 7\n"
+ "12345678 1 to 8\n"
+ "23456789 2 to 9\n"
+ "12456789 missing 3\n"
+ "01236789 missing 4,5\n"
+ "23456789 missing 0,1\n"
+ "1234567\n"
+ "12345\n"
+ "012345678\n"
+ "123456789\n"
+ "0123456789\n"
+ "98765432 9 to 2\n"
+ "87654321 8 to 1\n"
+ "76543210 7 to 0\n"
+ "98765321 missing 4\n"
+ "96543210 missing 7,8\n"
+ "98765432 missing 0,1\n\n\n\n";
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