Home > Back-end >  Regular Expression to Validate Monaco Number Plates
Regular Expression to Validate Monaco Number Plates

Time:04-21

I would like to have an expression to validate the plates of monaco. They are written as follows:

  • A123
  • 123A
  • 1234

I started by doing:

^[a-zA-Z0-9]{1}?[0-9]{2}?[a-zA-Z0-9]{1}$

But the case A12A which is false is possible with that.

CodePudding user response:

You can use

^(?!(?:\d*[a-zA-Z]){2})[a-zA-Z\d]{4}$

See the regex demo. Details:

  • ^ - start of string
  • (?!(?:\d*[a-zA-Z]){2}) - a negative lookahead that fails the match if there are two occurrences of any zero or more digits followed with two ASCII letters immediately to the right of the current location
  • [a-zA-Z\d]{4} - four alphanumeric chars
  • $ - end of string.

CodePudding user response:

You can write the pattern using 3 alternatives specifying all the allowed variations for the example data:

^(?:[a-zA-Z][0-9]{3}|[0-9]{3}[a-zA-Z]|[0-9]{4})$

See a regex demo.

Note that you can omit {1} and

To not match 2 chars A-Z you can write the alternation as:

^(?:[a-zA-Z]\d{3}|\d{3}[a-zA-Z\d]|\d[a-zA-Z\d][a-zA-Z\d]\d)$

See another regex demo.

CodePudding user response:

So it needs 3 connected digits and 1 letter or digit.

Then you can use this pattern :

^(?=.?[0-9]{3})[A-Za-z0-9]{4}$

The lookahead (?=.?[0-9]{3}) asserts the 3 connected digits.

Test on Regex101 here

  • Related