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):
At the moment, I only have this working:
([A-Z]){2}-([0-9]){2}-([0-9]){2}
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With