New Mercosul License Plates Regex Announcement

New Mercosul labels have the following rules:

  • Must have 7 alphanumeric digits, in which:
    • 4 - Letters (AZ)
    • 3 - digits (\ d)
  • Letters and numbers can be shuffled anyway.

Therefore, the following texts apply: AB123CD, 1A2B3CD, 123ABCD, ABCD123

And they are not valid: ABC1234D, ABCDE12, ABC123, etc.

I know I can achieve this with code just by checking the size of the string and the number of numbers and letters, but this problem makes me wonder if this can also be achieved via Regex.

All I could think of was to generate all features like (\ d {3} [AZ] {4}), (\ d {2} [AZ] {4} \ d) and use | join them, which is not entirely practical given the large number of combinations, any other thoughts? Or is it just a case where Regex is not an option?

Edited after answer:

As @stribes wrote, this is a typical use case for Ahead.

I found the link a very helpful source

And here is an example on how to perform password checks using lookarounds

+3


source to share


3 answers


You can perform this check with the following regular expression:

^(?=(?:.*[0-9]){3})(?=(?:.*[A-Z]){4})[A-Z0-9]{7}$

      

Explanation

  • (?=(?:.*[0-9]){3})

    - Positive look to check for 3 digits
  • (?=(?:.*[A-Z]){4})

    - Positive look at 4 letters
  • [A-Z0-9]{7}

    - A valid string of 7 alphanumeric characters (not including _

    which is part of the pattern \w

    )


A separate line must be passed in for this test to pass because of the anchors ( ^

and $

).

You can add case insensitivity by adding the appropriate option.

Tested in Expresso:

enter image description here

+6


source


For this kind of thing, it would be easier to look at it from a different direction (in psedudo-code):



letters = regex(s/[^a-z]//, license_plate);
numbers = regex(s/[^\d]//, license_plate);

if (length(letters) == 4) && (length(numbers) == 3)) {
   plate is ok
}

      

+1


source


I don't like the style.

bool CheckPlate(string str)
{
    int let = 0;
    int dig = 0;
    foreach (ch letter in input)
    {
        let += (int) IsLetter(ch);
        dig += (int) IsDigit(ch);   
    }
    if(let == 4 && dig == 3 && str.Lenght() == 7)
        return true;
    else
      return false;
}

      

0


source







All Articles