代码之家  ›  专栏  ›  技术社区  ›  AER

Regex for Address在Regex 101(Python)中工作,而不是在Python中使用re.match?

  •  0
  • AER  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我有以下Python脚本(在Jupyter中),它应该使用regex提取地址信息(在此步骤之前,单元号已经被清除,街道类型被缩写):

    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 说它应该工作,看看正则表达式,我认为它也应该工作。。。

    它应该打印出以下内容:

    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
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   ethguo    6 年前

    根据 the docs , re.match 检查是否匹配 在字符串的开头 .

    既然你在寻找一个从绳子中间开始的匹配,你会想要 re.search 相反。