'Regular Expression to Validate Monaco Number Plates
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.
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wiktor Stribiżew |
| Solution 2 | |
| Solution 3 | LukStorms |
