Help required with RegEx - formatting vehicle registration numbers

I am looking for some advice and help with regards to user entry of vehicle registration numbers in the UK (This idea would also apply to the UK postal codes).

In the UK there are many different forms of vehicle registration number, always alphanumeric (capitals) and always with a single space at a predesignated position, for instance

  • BD67 GTY (current)
  • G228 TNX (typically from the 60s, 70s, 80s)
  • NJZ 9251 (for Northern Ireland)
  • 7654 NB (pre-1960s)

And the following RegEx captures (most) of them. My problem is that when data is entered by a user, more often than not they don’t understand the importance of the formatting, or they are simply lazy! So for the correct registration of BD67 GTY the user may type

  • BD67GTY
  • BD 67 GTY
  • bd67gty

but we need to store the correctly formatted BD67 GTY in the database.

What is the best process to go from a form to database insert or update using RegEx?

I assume the first thing is to Trim the start and end of the string, then remove any spaces to give a pure alphanumeric string. But then how do I use the RegEx to deliver the correct format for storing in the database? What is the best process?

(?<Current>^[A-Z]{2}[0-9]{2}[A-Z]{3}$)|(?<Prefix>^[A-Z][0-9]{1,3}[A-Z]{3}$)|(?<Suffix>^[A-Z]{3}[0-9]{1,3}[A-Z]$)|(?<DatelessLongNumberPrefix>^[0-9]{1,4}[A-Z]{1,2}$)|(?<DatelessShortNumberPrefix>^[0-9]{1,3}[A-Z]{1,3}$)|(?<DatelessLongNumberSuffix>^[A-Z]{1,2}[0-9]{1,4}$)|(?<DatelessShortNumberSufix>^[A-Z]{1,3}[0-9]{1,3}$)

Hi @UKRiggers,
Can I just check why you would need to store the registrations in the correct format? You could always, as you have pointed out above, trim them, remove spaces, apply regex for validation and save them. If you need specific formatting when displaying, you could apply it then.

To format:
You could look for the position of the first integer in the trimmed string. If position 4 (index 3) add a space at position 4 (ind.3) else the space appears at position 5 (ind.4)

I hope this helps
Ben

Thanks @bpj for the reply, you are making me think and question my own sanity! :crazy_face:

Of course the best option would be to store trimmed and no spaces, much easier to manipulate and compare, and then to display using RegEx filter.

I haven’t used the Wappler to filter and display using RegEx but I am sure it’s simple enough. Cheers.

There is a PHP function you could use:
$pos = strcspn( $str , ‘0123456789’ );

It will return the first position of any character (in this case integers) found in the second parameter. You could then use that to add the white space:
$replacement = " ";
substr_replace($str, $replacement, $pos, 0);

This could be done in your script before inserting/updating or after retrieving the value. Up to you, really.

I’m sure there’s also equivalent JS functions you could use - I haven’t tried anything in Wappler like this.

1 Like