Regex for a pattern XXYYZZ

You can use

s.matches("(\\p{Alnum})\\1(?!\\1)(\\p{Alnum})\\2(?!\\1|\\2)(\\p{Alnum})\\3")

See the regex demo.

Details

  • \A - start of string (it is implicit in String#matches) - the start of string
  • (\p{Alnum})\1 - an alphanumeric char (captured into Group 1) and an identical char right after
  • (?!\1) - the next char cannot be the same as in Group 1
  • (\p{Alnum})\2 - an alphanumeric char (captured into Group 2) and an identical char right after
  • (?!\1|\2) - the next char cannot be the same as in Group 1 and 2
  • (\p{Alnum})\3 - an alphanumeric char (captured into Group 3) and an identical char right after
  • \z - (implicit in String#matches) - end of string.

RegexPlanet test results:

enter image description here


Since you know a valid pattern will always be six characters long with three pairs of equal characters which are different from each other, a short series of explicit conditions may be simpler than a regex:

public static boolean checkPattern(String str) {
   return str.length() == 6 &&
          str.charAt(0) == str.chatAt(1) &&
          str.charAt(2) == str.chatAt(3) &&
          str.charAt(4) == str.chatAt(5) &&
          str.charAt(0) != str.charAt(2) &&
          str.charAt(0) != str.charAt(4) &&
          str.charAt(2) != str.charAt(4);
}

Would the following work for you?

^(([A-Za-z\d])\2(?!.*\2)){3}$

See the online demo


  • ^ - Start string anchor.
  • (- Open 1st capture group.
    • ( - Open 2nd capture group.
      • [A-Za-z\d] - Any alphanumeric character.
      • ) - Close 2nd capture group.
    • \2 - Match exactly what was just captured.
    • (?!.*\2) - Negative lookahead to make sure the same character is not used elsewhere.
    • ) - Close 1st capture group.
  • {3} - Repeat the above three times.
  • $ - End string anchor.

Tags:

Java

String

Regex