正则表达式重新定义

2024-10-01 13:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python,遇到了一些重定义错误,我知道它们是重定义的,但是逻辑上不可能达到这个目的,因为它是一个or。有办法绕过这个问题吗?我很感谢你事先的帮助

/python-2.5/lib/python2.5/复制“,第233行,in\u compile 引发错误,v#无效表达式 sre公司_常量.错误:将组名'id'重新定义为组9;was group 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


Tags: 目的reinfoid定义more错误逻辑
3条回答

正则表达式语法不允许多次出现同名组,未“到达”的组在一个匹配项上定义为“空”(无)。在

因此,您必须将这些名称更改为dob0dob1dob2和{}、id1id2(然后,您可以很容易地“折叠”这些键集,以便在您从匹配的组字典中获得所需的dict)。在

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

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

对于其他语句也是类似的,并将计算PERSON_RE的语句中出现的三个DOB_RE更改为DOB_RE(0)DOB_RE(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'}

我本来打算用Each类发布一个pyparsing示例(它可以挑选出任何顺序的表达式),但是后来我发现其中有混杂的垃圾,因此使用searchString搜索字符串似乎更合适。这引起了我的兴趣,因为searchString返回一个ParseResults序列,每个匹配项对应一个(包括任何相应的命名结果)。所以我想,“如果我用sum组合返回的ParseResults怎么办?真是个黑客!”呃,“真新奇!”下面是一个从未见过的pyparsing黑客:

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

给出这个输出:

^{pr2}$

但我也会说regex。这里有一个使用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

相关问题 更多 >