Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Mercosul License Plates Regex

Tags:

c#

.net

regex

New Mercosul License Plates have the following rules:

  • Must have 7 alphanumeric digits, in which:
    • 4 are letters (A-Z)
    • 3 are digits (\d)
  • Letters and Digits can be shuffled in anyway.

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

like image 963
Rodrigo López Avatar asked Apr 23 '15 21:04

Rodrigo López


1 Answers

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:

enter image description here

like image 154
Wiktor Stribiżew Avatar answered Sep 30 '22 14:09

Wiktor Stribiżew