'How can I match Portuguese license plates in a single regular expression?

I was building a regex to validate Portuguese license plates however, the old ones come in a different format, and I would like to know if it is possible to validate all of the possibilities with just one regex?

These are the possibilities, any other is invalid (i.e.: 00-A0-00):

  • 00-00-AA
  • AA-00-00
  • 00-AA-00

At the moment, I only have this working:

([A-Z]){2}-([0-9]){2}-([0-9]){2}



Solution 1:[1]

This works:

((?:[A-Z]{2}-\d{2}-\d{2})|(?:\d{2}-[A-Z]{2}-\d{2})|(?:\d{2}-\d{2}-[A-Z]{2}))

Demo

Anchors are better (with m flag):

(^(?:[A-Z]{2}-\d{2}-\d{2})|(?:\d{2}-[A-Z]{2}-\d{2})|(?:\d{2}-\d{2}-[A-Z]{2})$)

Demo 2

Solution 2:[2]

Just Use Alternation

Depending on your regex engine, you may have to vary a few things, but in general the easiest thing to do is to simply provide three alternations. For example:

\d{2}-\d{2}-[[:alpha:]]{2}|[[:alpha:]]{2}\d{2}-\d{2}|\d{2}-[[:alpha:]]{2}-\d{2}

This works fine for me in Ruby against your sample inputs. YMMV.

Solution 3:[3]

Well, you can always OR the 3 of them

([A-Z]){2}-(\d){2}-(\d){2}|(\d){2}-([A-Z]){2}-(\d){2}|(\d){2}-(\d){2}-([A-Z]){2}

Solution 4:[4]

Now we have in Portugal a new combination AA-00-AA https://www.razaoautomovel.com/2020/03/novas-matriculas-em-cirulacao (English google translated)(started at 2 de march of 2020, you can see the official law)

Using dawg answer now is

(^(?:[A-Z]{2}-\d{2}-\d{2})|(?:\d{2}-[A-Z]{2}-\d{2})|(?:\d{2}-\d{2}-[A-Z]{2})|(?:[A-Z]{2}-\d{2}-[A-Z]{2})$)

Solution 5:[5]

for that new Portugal plate combination I made this one:

/([A-Z]{2}|[0-9]{2})-([A-Z]{2}|[0-9]{2})-([A-Z]{2}|[0-9]{2})/gm

tested in: regex101

Solution 6:[6]

Would it be easier to create another REGEX for Diplomatic licence plates in Portugal and test the 2 conditions or to change the Regex above to consider this plates. Here is the format where X stands for a number and the other are fixed letters. XXX-CDXXX and XXX-FMXXX.

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 dawg
Solution 2 Todd A. Jacobs
Solution 3 ffflabs
Solution 4 ruirodrigues1971__
Solution 5 tfig-dev
Solution 6 Miguel