英国邮政编码正则表达式(全面)

时间:2020-03-06 15:03:17  来源:igfitidea点击:

我正在使用一个正则表达式,它将仅在输入字符串内验证完整的复杂英国邮政编码。所有不常见的邮政编码形式都必须像往常一样覆盖。例如:

火柴

  • CW3 9SS
  • SE5 0EG
  • SE50EG
  • se5 0eg
  • WC2H 7LT

没有比赛

  • aWC2H 7LT
  • WC2H 7LTa
  • WC2H

是否有用于这种事情的正式或者半官方的正则表达式?关于格式化这些格式并将其存储在数据库中还有其他建议吗?

解决方案

^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$
Regular expression to match valid UK
  postcodes. In the UK postal system not
  all letters are used in all positions
  (the same with vehicle registration
  plates) and there are various rules to
  govern this. This regex takes into
  account those rules. Details of the
  rules: First half of postcode Valid
  formats [A-Z][A-Z][0-9][A-Z]
  [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9]
  [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z]
  [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions
  Position - First. Contraint - QVX not
  used Position - Second. Contraint -
  IJZ not used except in GIR 0AA
  Position - Third. Constraint -
  AEHMNPRTVXY only used Position -
  Forth. Contraint - ABEHMNPRVWXY Second
  half of postcode Valid formats
  [0-9][A-Z][A-Z] Exceptions Position -
  Second and Third. Contraint - CIKMOV
  not used

http://regexlib.com/REDetails.aspx?regexp_id=260

我建议我们查看英国政府数据标准中的邮政编码[现在链接已消失; XML存档,请参阅Wikipedia进行讨论]。这里有关于数据的简短描述,添加的xml模式提供了一个正则表达式。它可能不完全是我们想要的,但将是一个很好的起点。 RegEx与XML略有不同,因为给定的定义允许使用A9A 9AA格式的第三位置的P字符。

英国政府提供的RegEx为:

([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})

正如Wikipedia讨论中指出的那样,这将允许使用一些非真实的邮政编码(例如,以AA,ZY开头的邮政编码),并且确实提供了我们可以尝试的更严格的测试。

邮政编码的前半部分有效格式

  • [A-Z] [A-Z] [0-9] [A-Z]
  • [A-Z] [A-Z] [0-9] [0-9]
  • [A-Z] [0-9] [0-9]
  • [A-Z] [A-Z] [0-9]
  • [A-Z] [A-Z] [A-Z]
  • [A-Z] [0-9] [A-Z]
  • [A-Z] [0-9]

例外情况
位置1 QVX未使用
位置2 IJZ仅在GIR 0AA中不使用
仅使用位置3 AEHMNPRTVXY
位置4 ABEHMNPRVWXY

邮编的后半部分

  • [0-9] [A-Z] [A-Z]

例外情况
位置2 + 3 CIKMOV未使用

请记住,并非所有可能的代码都已使用,因此此列表是有效代码的必要但非充分条件。仅将其与所有有效代码的列表进行匹配会更容易吗?

看一下此页面上的python代码:

http://www.brunningonline.net/simon/blog/archives/001292.html

I've got some postcode parsing to do. The requirement is pretty simple; I have to parse a postcode into an outcode and (optional) incode. The good new is that I don't have to perform any validation - I just have to chop up what I've been provided with in a vaguely intelligent manner. I can't assume much about my import in terms of formatting, i.e. case and embedded spaces. But this isn't the bad news; the bad news is that I have to do it all in RPG. :-(
  
  Nevertheless, I threw a little Python function together to clarify my thinking.

我用它来为我处理邮政编码。