【问题标题】:Regex for Address working in Regex 101 (Python) not in Python using re.match? [duplicate]Regex for Address 在 Regex 101 (Python) 中工作,而不是在 Python 中使用 re.match? [复制]
【发布时间】:2019-11-15 06:10:13
【问题描述】:

我有以下 Python 脚本(在 Jupyter 中),它应该使用正则表达式提取地址信息(在此步骤之前已清理单元号并且街道类型已缩写):

type_opts = r"Terrace|Way|Walk|St|Rd|Ave|Cl|Ct|Cres|Blvd|Dr|Ln|Pl|Sq|Pde"
road_attrs_pattern = r"(?P<rd_no>\w?\d+(\-\d+)?\w?\s+)(?P<rd_nm>[a-zA-z \-]+)(?#\s+(?P<rd_tp>" + type_opts + ")"
print("Road Attr Pattern: ", road_attrs_pattern)
road_attrs = re.match(road_attrs_pattern, proc_addr)
road_num = road_attrs.group('rd_no').strip()
print("Road number: ", road_num)
road_name = road_attrs.group('rd_nm').strip()
print("Road name: ", road_name)
road_type = road_attrs.group('rd_tp').strip()
print("Road type: ", road_type)

我正在使用这个地址:

Burrah lodge, 15 Anne Jameson Pl

这将导致以下打印输出:

Road Attr Pattern:  (?P<rd_no>\w?\d+(\-\d+)?\w?\s+)(?P<rd_nm>[a-zA-z \-]+)(?#\s+(?P<rd_tp>Terrace|Way|Walk|St|Rd|Ave|Cl|Ct|Cres|Blvd|Dr|Ln|Pl|Sq|Pde)

然后抛出一个错误,说街道号码不可用AttributeError: 'NoneType' object has no attribute 'group'

但是,Regex101 here 中的复制粘贴表示它应该可以工作,并且查看 Regex,我认为它也应该可以工作......

它应该打印出以下内容:

Road Attr Pattern:  (?P<rd_no>\w?\d+(\-\d+)?\w?\s+)(?P<rd_nm>[a-zA-z \-]+)(?#\s+(?P<rd_tp>Terrace|Way|Walk|St|Rd|Ave|Cl|Ct|Cres|Blvd|Dr|Ln|Pl|Sq|Pde)
Road number: 15
Road name: Anne Jameson
Road type: Pl

【问题讨论】:

    标签: python regex python-3.x jupyter regex-group


    【解决方案1】:

    根据the docsre.match 在字符串的开头检查匹配

    由于您正在寻找从字符串中途开始的匹配项,因此您需要re.search

    【讨论】:

    • 好的,不好意思,谢谢你的帮助。我也会调整问题以帮助其他人指出它......
    猜你喜欢
    • 2015-05-24
    • 2021-07-25
    • 2019-11-19
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多