-1

Trying to write Javax validation regex pattern to match any string with the following:

  • Doesn’t start with 001, 002 or 003
  • Starts with 3 digits followed by a hyphen, which is then followed by any letter, number, hyphen, $, + or _
  • Contains 35-50 characters in total

What I have so far which works for the 2nd and 3rd requirements that I listed above:

“^[\w\-+\$_]{35,50}$”

Now I am trying to add the 1st requirement which I listed above, however I cannot seem to get it to work:

”^[?!(001|002|003)\-+\$_]{35,50}$”

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
monkey123
  • 133
  • 1
  • 1
  • 10

1 Answers1

0

I would use String#matches here with the following regex pattern:

^(?!00[123])\d{3}-[A-Za-z0-9$+_-]{35,50}$

This uses a negative lookahead at the beginning of the pattern to assert that the input does not begin with 001, 002, or 003.

Sample Java code:

String input = "123-12323456780abcdefghij1234567890abcde";
if (input.matches("(?!00[123])\\d{3}-[A-Za-z0-9$+_-]{35,50}")) {
    System.out.println("MATCH");
}

Note carefully that when using String#matches we don't need the ^ and $ starting/ending anchors. This is because matches() implicitly applies the input regex pattern against the entire string.

Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263