2012-09-08 35 views
0

這是我的正則表達式:爲什麼我用ASCII組名稱得到「sre_constants.error:組名中的壞字符」?

(?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模式(# --*-- Encoding: UTF-8 --*--)。

回答

8

您正在使用(?P=<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> 

這可能是你的意思擺在首位的事情。 :-)

相關問題