Since @Manwal’s answer doesn’t exactly do what it should, here is my attempt at shortening the regex for OP:
(?:^[AC-FHKNPRTV-Y][0-9]{2}|D6W)[ -]?[0-9AC-FHKNPRTV-Y]{4}$
Updated version supporting the A65 B2CD postcodes – (?:^[AC-FHKNPRTV-Y][0-9]{2}|D6W)[ -]?[0-9AC-FHKNPRTV-Y]{4}$
This is basically what your Regex is, with a few changes:
- Removed commas. You do not need commas to list items inside
[]
brackets. - Added ranges where possible and where it would save some space (
C-F
,V-Y
). Elsewhere it’s not beneficial to add ranges, as it won’t make regex shorter. - You do not need to escape a space. ” ” in regex is literal.
- You also do not need to escape the dash if it’s the last character in character class (square brackets)
- The first part of the regex is now in a non-capturing group to allow ORing it with the only possible letter for 3rd position, the “D6W” case.
It is also possible to deal with D6W
exclusively with lookbehind, but this is more of an art than regex.
See Regex Demo: here
You can also invert the character class to not include given characters, and while it doesn’t make the regex shorter, it’s also worth noting. However, you need to make sure that other characters (like dots, commas) are not included too. I do it by adding the \W
token.
You can try it here