Regular expression to validate car plate

Asked

Viewed 1,109 times

1

I would like a regular loan to validate license plates.

Today in Brazil we have 2 models: the old and Brazil. The difference is that in the 5th character, in the South is only text while in the old it is only number, so to make a rule that accepts both in this field you must accept text and number in this 5th house.

Ex. of logic:

Something like:

N - números
T - Texto
# - Ambos caracteres

TTTN#NN

I did so:

^([^0-9][^0-9][^0-9][0-9][A-Za-z0-9][0-9][0-9])

That worked on this website.

The question: is that right? It has to be shortened?

1 answer

5


It’s not quite right because [^0-9] accepted whichever character other than a digit from 0 to 9. That is, it can accept space, punctuation marks, accented letters and other alphabets, emojis, etc (see here).

If you want to limit only letters from A to Z without an accent, use [a-zA-Z], or [A-Z] if you only want capital letters.

For repetitions, use quantifiers to indicate the exact quantity:

^[a-zA-Z]{3}[0-9][A-Za-z0-9][0-9]{2}$

In the case, {3} means "exactly 3 occurrences", so [a-zA-Z]{3} means "exactly 3 letters A to Z, uppercase or lowercase". Therefore, [0-9]{2} means "exactly 2 digits from 0 to 9".

I also included the bookmark $ which indicates the end of the string, so I guarantee that there can be no more characters after (you used the ^, which indicates the start of the string, but if you do not have the $, regex accepts strings that have more characters after).

I also removed the parentheses because it doesn’t seem necessary in this case.


You can also use the shortcut \d for digits. But depending on the language/engine used, it can also pick up other characters, such as from this list. As the language/engine was not specified, keep [0-9] even, which will surely only accept the digits from 0 to 9, regardless of the language.

  • 2

    more than one answer to a class, if I could give +2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.