I have been given the following pattern for a UK Postcode:
([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)
Can anyone break this down for me?
I have been given the following pattern for a UK Postcode:
([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)
Can anyone break this down for me?
Here it is:
NODE EXPLANATION
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
[A-PR-UWYZ0-9] any character of: 'A' to 'P', 'R' to
'U', 'W', 'Y', 'Z', '0' to '9'
----------------------------------------------------------------------
[A-HK-Y0-9] any character of: 'A' to 'H', 'K' to
'Y', '0' to '9'
----------------------------------------------------------------------
[AEHMNPRTVXY0-9]? any character of: 'A', 'E', 'H', 'M',
'N', 'P', 'R', 'T', 'V', 'X', 'Y', '0'
to '9' (optional (matching the most
amount possible))
----------------------------------------------------------------------
[ABEHMNPRVWXY0-9]? any character of: 'A', 'B', 'E', 'H',
'M', 'N', 'P', 'R', 'V', 'W', 'X', 'Y',
'0' to '9' (optional (matching the most
amount possible))
----------------------------------------------------------------------
{1,2} ' ' (between 1 and 2 times (matching the
most amount possible))
----------------------------------------------------------------------
[0-9] any character of: '0' to '9'
----------------------------------------------------------------------
[ABD-HJLN-UW-Z]{2} any character of: 'A', 'B', 'D' to 'H',
'J', 'L', 'N' to 'U', 'W' to 'Z' (2
times)
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
GIR 0AA 'GIR 0AA'
----------------------------------------------------------------------
) end of \1
debuggex.com is a really useful resource for debugging regular expressions:
I'm actually a bigger fan of either of the other two answers than the ones I'm about to list, but the more the merrier:
http://regex101.com/ - will give a good breakdown/explanation
http://www.regexper.com/ - will produce a lovely railroad diagram:
The following answers are also worth a read for slight alternatives/explanations: