【问题标题】:Python Regex some name + US AddressPython Regex 一些名称 + 美国地址
【发布时间】:2021-12-08 18:06:49
【问题描述】:

我有这些字符串:

WILLIAM SMITH 2345 GLENDALE DR RM 245 ATLANTA GA 30328-3474
LINDSAY SCARPITTA 655 W GRACE ST APT 418 CHICAGO IL 60613-4046

我想确保我得到的字符串和上面的字符串一样。
这是我的正则表达式:

[A-Z]+ [A-Z]+ [0-9]{3,4} [A-Z]+ [A-Z]{2,4} [A-Z]{2,4} [0-9]+ [A-Z]+ [A-Z]{2} [0-9]{5}-[0-9]{4}$

但是我的正则表达式只匹配第一个例子,不匹配第二个例子。

【问题讨论】:

  • 您还需要在“GRACE”之前检查“W”。您可以为此添加可选的(?:\w )?。 [A-Z]+ [A-Z]+ [0-9]{3,4} (?:\w )?[A-Z]+ [A-Z]{2,4} [A-Z]{2,4} [0-9]+ [A-Z]+ [A-Z]{2} [0-9]{5}-[0-9]{4}$ 或 (?:[A-Z] )?
  • 谢谢。请让我用其他样品测试一下。

标签: regex street-address


【解决方案1】:

这是 dawg 的带有捕获组的正则表达式:

^([A-Z]+[ \t]+[A-Z]+)[ \t]+(\d+)[ \t](.*)[ \t]+([A-Z]{2})[ \t]+(\d{5}(?:-\d{4}))$

这是url。

更新

抱歉,我忘记在 dawg 的正则表达式末尾删除非捕获组...
这是没有非捕获组的新正则表达式:regex101

【讨论】:

  • 感谢您的回答!
【解决方案2】:

试试这个:

^[A-Z]+[ \t]+[A-Z]+[ \t]+\d+.*[ \t]+[A-Z]{2}[ \t]+\d{5}(?:-\d{4})$

Demo

解释:

1. ^[A-Z]+[ \t]+[A-Z]+[ \t]+  Starting at the start of line, 
    two blocks of A-Z for the name 
    (however, names are often more complicated...)

2. \d+.*[ \t]+[A-Z]{2}[ \t]+  Using number start and 
   two letter state code at the end for the full address
   Cities can have spaces such as 'Miami Beach'

3. \d{5}(?:-\d{4})$  Zip code with optional -NNNN with end anchor

【讨论】:

  • 但是,当末尾没有 +4 位时,您的正则表达式确实有效。
  • 谢谢@dawg 的回答!这对我帮助很大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 2010-11-25
  • 2014-08-04
相关资源
最近更新 更多