Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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}

like image 951
Filipe YaBa Polido Avatar asked Aug 17 '14 00:08

Filipe YaBa Polido


People also ask

How do you read a Portuguese number plate?

The Portuguese car numbering system is an incremental system consisting of three groups of two characters, separated by dashes. The system began in 1937 with AA-10-00, then went on to 00-00-AA and recently changed over to 00-AA-00. When this sequence comes to an end, it will be replaced by the sequence AA-00-AA.

How do you read EU license plates?

Most license plates for countries in the European Union have a blue graphic strip on the left side of the plate. This strip has the country code in white – for Germany it is a “D” for Deutschland. Above the country code is the Flag of Europe with is the 12 golden stars in a circle.

What do EU license plates look like?

The common design consists of a blue strip on the left side of the plate. This blue strip has the EU flag symbol (twelve yellow stars), along with the country code of the member state in which the vehicle is registered.

Are all EU license plates the same?

Additionally, the E.U.'s system is much more organized than having to consult a wide database, as is in America. It all but guarantees that there are no two license plates with the same information throughout the European Union, whereas in America there can be overlaps from state to state.


2 Answers

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

like image 63
dawg Avatar answered Oct 02 '22 15:10

dawg


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.

like image 43
Todd A. Jacobs Avatar answered Oct 02 '22 15:10

Todd A. Jacobs