6

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}

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
Filipe YaBa Polido
  • 1,656
  • 1
  • 17
  • 39

6 Answers6

4

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

dawg
  • 98,345
  • 23
  • 131
  • 206
3

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.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
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}
ffflabs
  • 17,166
  • 5
  • 51
  • 77
2

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})$)
  • In this question you're not considering the Diplomatc licence plates in Portugal. Here is the format where X stands for a number and the other are fixed letters. XXX-CDXXX and XXX-FMXXX. – Miguel Apr 27 '21 at 17:19
1

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

tfig-dev
  • 21
  • 3
0

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.

Miguel
  • 81
  • 1
  • 8
  • 1
    (^(?:[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})|(\d{3}-CD\d{3})|(\d{3}-FM\d{3})$) The last two groups... Of course exists many special variants... – ruirodrigues1971__ Apr 29 '21 at 09:52