正则表达式重新定义错误

时间:2010-03-04 00:17:57

标签: python regex scripting

我正在使用python,并遇到一些重新定义错误,我知道它们是重新定义但在逻辑上它不可能达到它,因为它的一个或。有办法解决这个问题吗?我提前感谢任何帮助

_compile中的

/python-2.5/lib/python2.5/re.py“,第233行     引发错误,v#无效表达 sre_constants.error:将组名'id'重新定义为组9;是第6组


import re

DOB_RE =  "(^|;)DOB +(?P<dob>\d{2}-\d{2}-\d{4})"
ID_RE =   "(^|;)ID +(?P<id>[A-Z0-9]{12})"
INFO_RE = "- (?P<info>.*)"

PERSON_RE = "((" + DOB_RE + ".*" + ID_RE +  ")|(" + \
                   ID_RE  + ".*" + DOB_RE + ")|(" + \
                   DOB_RE + "|" + ID_RE + ")).*(" + INFO_RE + ")*"

PARSER = re.compile(PERSON_RE)

samplestr1 = garbage;DOB 10-10-2010;more garbage\nID PARI12345678;more garbage
samplestr2 = garbage;ID PARI12345678;more garbage\nDOB 10-10-2010;more garbage
samplestr3 = garbage;DOB 10-10-2010
samplestr4 = garbage;ID PARI12345678;more garbage- I am cool

3 个答案:

答案 0 :(得分:2)

正则表达式语法不允许多次出现同名组 - 未匹配的组在匹配时被定义为“空”(无)。

所以你必须改变那些名字,例如到dob0dob1dob2id0id1id2(然后你可以轻松地“折叠”这些密钥组来制作从匹配中获得组字典后你真正想要的字典。)

例如,将DOB_RE设为函数而不是常数,例如:

def DOB_RE(i): return "(^|;)DOB +(?P<dob%s>\d{2}-\d{2}-\d{4})" % i

和其他人类似,并将您计算DOB_RE的语句中PERSON_RE的三次出现更改为DOB_RE(0)DOB_RE(1)等(对于其他人也是如此) )。

答案 1 :(得分:2)

我原本打算使用Each类(它可以按任意顺序选择表达式)发布一个pyparsing示例,但后来我发现存在混合垃圾,因此使用searchString搜索字符串似乎更合适。这引起了我的兴趣,因为searchString返回一个ParseResults序列,每个匹配一个(包括任何相应的命名结果)。所以我想,“如果我将使用总和返回的ParseResults结合起来怎么样 - 什么是黑客!”,呃,“多么新颖!”所以这是一个前所未见的pyparsing hack:

from pyparsing import *
# define the separate expressions to be matched, with results names
dob_ref = "DOB" + Regex(r"\d{2}-\d{2}-\d{4}")("dob")
id_ref = "ID" + Word(alphanums,exact=12)("id")
info_ref = "-" + restOfLine("info")

# create an overall expression
person_data = dob_ref | id_ref | info_ref

for test in (samplestr1,samplestr2,samplestr3,samplestr4,):
    # retrieve a list of separate matches
    separate_results = person_data.searchString(test)

    # combine the results using sum
    # (NO ONE HAS EVER DONE THIS BEFORE!)
    person = sum(separate_results, ParseResults([]))

    # now we have a uber-ParseResults object!
    print person.id
    print person.dump()
    print

给出这个输出:

PARI12345678
['DOB', '10-10-2010', 'ID', 'PARI12345678']
- dob: 10-10-2010
- id: PARI12345678

PARI12345678
['ID', 'PARI12345678', 'DOB', '10-10-2010']
- dob: 10-10-2010
- id: PARI12345678


['DOB', '10-10-2010']
- dob: 10-10-2010

PARI12345678
['ID', 'PARI12345678', '-', ' I am cool']
- id: PARI12345678
- info:  I am cool

但我也说正则表达式。以下是使用re的类似方法。

import re

# define each individual re, with group names
dobRE = r"DOB +(?P<dob>\d{2}-\d{2}-\d{4})"
idRE = r"ID +(?P<id>[A-Z0-9]{12})"
infoRE = r"- (?P<info>.*)"

# one re to rule them all
person_dataRE = re.compile('|'.join([dobRE, idRE, infoRE]))

# using findall with person_dataRE will return a 3-tuple, so let's create 
# a tuple-merger
merge = lambda a,b : tuple(aa or bb for aa,bb in zip(a,b))

# let's create a Person class to collect the different data bits 
# (or if you are running Py2.6, use a namedtuple
class Person:
    def __init__(self,*args):
        self.dob, self.id, self.info = args
    def __str__(self):
        return "- id: %s\n- dob: %s\n- info: %s" % (self.id, self.dob, self.info)

for test in (samplestr1,samplestr2,samplestr3,samplestr4,):
    # could have used reduce here, but let's err on the side of explicity
    persontuple = ('','','')
    for data in person_dataRE.findall(test):
        persontuple = merge(persontuple,data)

    # make a person
    person = Person(*persontuple)

    # print out the collected results
    print person.id
    print person
    print

使用此输出:

PARI12345678
- id: PARI12345678
- dob: 10-10-2010
- info: 

PARI12345678
- id: PARI12345678
- dob: 10-10-2010
- info: 


- id: 
- dob: 10-10-2010
- info: 

PARI12345678
- id: PARI12345678
- dob: 
- info: I am cool

答案 2 :(得分:1)

也许在这种情况下,最好循环一个正则表达式列表。

>>> strs=[
... "garbage;DOB 10-10-2010;more garbage\nID PARI12345678;more garbage",
... "garbage;ID PARI12345678;more garbage\nDOB 10-10-2010;more garbage",
... "garbage;DOB 10-10-2010",
... "garbage;ID PARI12345678;more garbage- I am cool"]
>>> import re
>>> 
>>> DOB_RE =  "(^|;|\n)DOB +(?P<dob>\d{2}-\d{2}-\d{4})"
>>> ID_RE =   "(^|;|\n)ID +(?P<id>[A-Z0-9]{12})"
>>> INFO_RE = "(- (?P<info>.*))?"
>>> 
>>> REGEX = map(re.compile,[DOB_RE + ".*" + ID_RE + "[^-]*" + INFO_RE,
...                         ID_RE + ".*" + DOB_RE + "[^-]*" + INFO_RE,
...                         DOB_RE + "[^-]*" + INFO_RE,
...                         ID_RE + "[^-]*" + INFO_RE])
>>> 
>>> def get_person(s):
...     for regex in REGEX:
...         res = re.search(regex,s)
...         if res:
...             return res.groupdict()
... 
>>> for s in strs:
...     print get_person(s)
... 
{'dob': '10-10-2010', 'info': None, 'id': 'PARI12345678'}
{'dob': '10-10-2010', 'info': None, 'id': 'PARI12345678'}
{'dob': '10-10-2010', 'info': None}
{'info': 'I am cool', 'id': 'PARI12345678'}