New Mercosul License Plates have the following rules:
So the following texts are valid: AB123CD, 1A2B3CD, 123ABCD, ABCD123
And these are invalid: ABC1234D, ABCDE12, ABC123, etc
I know I can achieve this via code just checking the string size and count numbers and letters, but this problem make me wonder if that can also be achieved via Regex.
All I could think of is to generate all the possibilities like (\d{3}[A-Z]{4}) , (\d{2}[A-Z]{4}\d) and use | to join them, wich is not practical at all given the large amount of combinations, any other thoughts? Or this is just a case where Regex is a no go?
Edited after Answer:
As @stribizhev posted, this is a typical look Ahead use case.
I found this link a very useful source
And here's an example on how to perform password validations using lookarounds
You can achieve that validation with the following regex:
^(?=(?:.*[0-9]){3})(?=(?:.*[A-Z]){4})[A-Z0-9]{7}$
Explanation:
(?=(?:.*[0-9]){3})
- Positive look-ahead to check for 3 digits(?=(?:.*[A-Z]){4})
- Positive look-ahead to check for 4 letters[A-Z0-9]{7}
- Actual string consisting of 7 alphanumeric symbols (not including _
that is part of \w
pattern)An individual string should be passed to pass this test due to the anchors (^
and $
).
You can add case insensitive matching by adding the appropriate option.
Tested in Expresso:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With