这是我的正则表达式:
(?P=<streetname>[a-zæøå ]+)(?:[ ]+)(?P=<housenumber>\d+)(?:[ ]+),(?:[ ]+)(?P=<postalcode>\d{1,4})(?:[ ]+)(?P=<city>[a-zæøå ]+)
Run Code Online (Sandbox Code Playgroud)
所有组名只包含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模式(# --*-- Encoding: UTF-8 --*--).
您正在使用(?P=<name>...)模式,这意味着"匹配前面的名为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>
Run Code Online (Sandbox Code Playgroud)
这可能是你首先要做的.:-)
| 归档时间: |
|
| 查看次数: |
6842 次 |
| 最近记录: |