RegEx for matching UK Postcodes

前端 未结 30 2473
广开言路
广开言路 2020-11-22 01:38

I\'m after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For in

30条回答
  •  长发绾君心
    2020-11-22 01:47

    It looks like we're going to be using ^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$, which is a slightly modified version of that sugested by Minglis above.

    However, we're going to have to investigate exactly what the rules are, as the various solutions listed above appear to apply different rules as to which letters are allowed.

    After some research, we've found some more information. Apparently a page on 'govtalk.gov.uk' points you to a postcode specification govtalk-postcodes. This points to an XML schema at XML Schema which provides a 'pseudo regex' statement of the postcode rules.

    We've taken that and worked on it a little to give us the following expression:

    ^((GIR &0AA)|((([A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]))) &[0-9][ABD-HJLNP-UW-Z]{2}))$
    

    This makes spaces optional, but does limit you to one space (replace the '&' with '{0,} for unlimited spaces). It assumes all text must be upper-case.

    If you want to allow lower case, with any number of spaces, use:

    ^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$
    

    This doesn't cover overseas territories and only enforces the format, NOT the existence of different areas. It is based on the following rules:

    Can accept the following formats:

    • “GIR 0AA”
    • A9 9ZZ
    • A99 9ZZ
    • AB9 9ZZ
    • AB99 9ZZ
    • A9C 9ZZ
    • AD9E 9ZZ

    Where:

    • 9 can be any single digit number.
    • A can be any letter except for Q, V or X.
    • B can be any letter except for I, J or Z.
    • C can be any letter except for I, L, M, N, O, P, Q, R, V, X, Y or Z.
    • D can be any letter except for I, J or Z.
    • E can be any of A, B, E, H, M, N, P, R, V, W, X or Y.
    • Z can be any letter except for C, I, K, M, O or V.

    Best wishes

    Colin

提交回复
热议问题