我正在使用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
正则表达式语法不允许多次出现同名组,未“到达”的组在一个匹配项上定义为“空”(无)。在
因此,您必须将这些名称更改为}、
dob0
、dob1
、dob2
和{id1
、id2
(然后,您可以很容易地“折叠”这些键集,以便在您从匹配的组字典中获得所需的dict)。在例如,将
DOB_RE
设为函数而不是常量,例如:对于其他语句也是类似的,并将计算
PERSON_RE
的语句中出现的三个DOB_RE
更改为DOB_RE(0)
,DOB_RE(1)
等(其他语句也是如此)。在也许在这种情况下,最好循环使用正则表达式列表。在
我本来打算用Each类发布一个pyparsing示例(它可以挑选出任何顺序的表达式),但是后来我发现其中有混杂的垃圾,因此使用
searchString
搜索字符串似乎更合适。这引起了我的兴趣,因为searchString
返回一个ParseResults序列,每个匹配项对应一个(包括任何相应的命名结果)。所以我想,“如果我用sum组合返回的ParseResults怎么办?真是个黑客!”呃,“真新奇!”下面是一个从未见过的pyparsing黑客:给出这个输出:
^{pr2}$但我也会说regex。这里有一个使用re的类似方法
有了这个输出:
相关问题 更多 >
编程相关推荐