这是我的正则表达式:
(?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 expression
sre_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>
这可能是您最初打算做的。 :-)
