Caballero Caballero - 28 days ago 5x
MySQL Question

Regex to get area and district codes from UK postcodes

Basically, I need a regex that would match first sequence of letters in UK postcode (easy) and another regex which would match the following number (not so easy).

Examples of possible combinations and matches:

AA9A 9AA regex1: AA regex2: 9
A9A 9AA regex1: A regex2: 9
A9 9AA regex1: A regex2: 9
A99 9AA regex1: A regex2: 99
AA9 9AA regex1: AA regex2: 9
AA99 9AA regex1: AA regex2: 99

Spaces in poscodes are only there for clarity, they might or might not be there, therefor must be disregarded.

I could use some help with these two regular expressions, especially regex2 (matching the number). By the way, I'm gonna be running this in MySQL 5.6

UPDATE: Just to note: last 3 characters will always be ignored no matter what, that's the only pattern that always applies - it should be visible from my examples.

UPDATE2: Sorry if I wasn't clear enough before - I don't need to validate the post codes, I need to extract area and district codes.

UPDATE3: Just to emphasize again: white space must be disregarded, it could be
AA99 9AA
- in both cases the regex2 (extract number) should be

UPDATE4: Thanks for all your answers, unfortunately I just found out that MySQL can't extract regex matches. Way to go, MySQL, proving to be useless yet again.


You can use this regex:


and use matched group #1 and #2