How to create regex pattern for Number Patterns like AAAABBB and AAABBCC

Viewed 101

How to create regex pattern for Number Patterns like AAAABBB and AAABBCC. Number matched in the first group should not be considered in the 2nd and later groups.


Here:
A = [0-9] Any number between 0 to 9
B = [0-9] Any number between 0 to 9 excluding A
C = [0-9] Any number between 0 to 9 excluding A and B

For example : 5555333, 7777999, 2225588, 1113377 etc. I want to find such numbers from the bigger number range using java regex.

1 Answers

I believe this does what you want. It captures the desired digit, followed by 0 or more of the same digit, not followed by any previous digit using back references in the negative look ahead assertions.

String pat = "(\\d)\\1*(?:(\\d)\\2*(?!\\1)){1,2}";
long[] data = {112233, 123333, 888777555, 999666, 222111222,222222, 111122221, 11223344,44442222,444455522, 522212121};
for (long i : data) {
    String s = Long.toString(i);
    System.out.printf("%12s - %s%n", s, s.matches(pat) ? "Valid" : "Invalid");
}

Prints

      112233 - Valid
      123333 - Valid
   888777555 - Valid
      999666 - Valid
   222111222 - Invalid
      222222 - Valid
   111122221 - Invalid
    11223344 - Invalid
    44442222 - Valid
   444455522 - Valid
   522212121 - Invalid
Related