问题
I have this pattern in a php project I inherited.
^(([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}))$
Which works fine for all practical purposes when used to validate a full British postcode (eg LE1 1AA). However I need to tweak it to allow for partial postcodes like LE1, SN5 ect where only the first segment is provided.
Can anyone suggest how to make the adjustment?
回答1:
This should do the job
^(([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})?))$
http://ideone.com/lLg4uD
回答2:
First of all:
UK postal code correct regex is (more or less seems to be similar to your, but I have no time/will to check every possible case):
^(([A-Z]\d{2}[A-Z]{2})|([A-Z]\d{3}[A-Z]{2})|([A-Z]{2}\d{2}[A-Z]{2})|([A-Z]{2}\d{3}[A-Z]{2})|([A-Z]\d[A-Z]\d[A-Z]{2})|([A-Z]{2}\d[A-Z]\d[A-Z]{2})|(GIR0AA))$
According to the geonames' data (Official iso code of UK is GB, UK is reserved, geocode id: 2635167)
Always according to this data the format is:
@# #@@|@## #@@|@@# #@@|@@## #@@|@#@ #@@|@@#@ #@@|GIR0AA
Where, IIRC, the @
stands for character and the #
for numbers.
So to retrieve only the first part of the GB's postal codes your format will become:
@#|@##|@@#|@@##|@#@|@@#@|GIR
Assuming that this is the partial check you want to achieve the regex will become:
^(([A-Z]\d)|([A-Z]\d{2})|([A-Z]{2}\d)|([A-Z]{2}\d{2})|([A-Z]\d[A-Z])|([A-Z]{2}\d[A-Z])|(GIR))$
Of course you may want to support both uppercase and lower case characters, if this is the case, just change all the [A-Z]
occurrences to [A-Za-z]
and GIR
to [gG][iI][rR]
Remember that this will validate just the format of your postal codes not if the code exist, to do so you can download the information from geonames.org and parse them into a database for a later check.
来源:https://stackoverflow.com/questions/23930574/pattern-match-a-partial-british-postcode