gpt4 book ai didi

python - 为什么我得到带有 ASCII 组名的 "sre_constants.error: bad character in group name"?

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:43 25 4
gpt4 key购买 nike

这是我的正则表达式:

(?P=<streetname>[a-zæøå ]+)(?:[ ]+)(?P=<housenumber>\d+)(?:[ ]+),(?:[ ]+)(?P=<postalcode>\d{1,4})(?:[ ]+)(?P=<city>[a-zæøå ]+)

所有组名都只包含ASCII字符,为什么会报错?

Traceback (most recent call last):  File "addrtools.py", line 46, in     main()  File "addrtools.py", line 43, in main    extract_address('Testaddress 15B, 1234 Oslo')  File "addrtools.py", line 35, in extract_address    match = re.match(pat_full, string)  File "/Users/tomas/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/re.py", line 137, in match    return _compile(pattern, flags).match(string)  File "/Users/tomas/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/re.py", line 242, in _compile    raise error, v # invalid expressionsre_constants.error: bad character in group name

我已确认 pat_full 确实包含上述​​正则表达式。此外,我的文档以 UTF-8 编码并设置为 UTF-8 模式(# --*-- 编码:UTF-8 --*--)。

最佳答案

您正在使用 (?P=<name>...) patterns,这意味着“匹配任何与早期名为 name 的组匹配的文本”。但是您没有像 streetname 这样的组之前定义。

删除 =使它们成为真正的命名组:

>>> re.compile('(?P<streetname>[a-zæøå ]+)(?:[ ]+)(?P<housenumber>\d+)(?:[ ]+),(?:[ ]+)(?P<postalcode>\d{1,4})(?:[ ]+)(?P<city>[a-zæøå ]+)')
<_sre.SRE_Pattern object at 0x102e6a620>

这可能是您最初打算做的。 :-)

关于python - 为什么我得到带有 ASCII 组名的 "sre_constants.error: bad character in group name"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12330519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com