为了清楚起见,我一直在寻找一种同时编译多个正则表达式的方法。
为简单起见,假设每个表达式都应采用 (.*) something (.*)
格式。
测试的表达式不会超过 60 个。
如图所示here ,我终于写下了以下内容。
import re
re1 = r'(.*) is not (.*)'
re2 = r'(.*) is the same size as (.*)'
re3 = r'(.*) is a word, not (.*)'
re4 = r'(.*) is world know, not (.*)'
sentences = ["foo2 is a word, not bar2"]
for sentence in sentences:
match = re.compile("(%s|%s|%s|%s)" % (re1, re2, re3, re4)).search(sentence)
if match is not None:
print(match.group(1))
print(match.group(2))
print(match.group(3))
由于正则表达式由竖线分隔,我认为一旦匹配到规则它会自动退出。
执行代码,我有
foo2 is a word, not bar2
None
None
但是通过在 re.compile 中反转 re3 和 re1 match = re.compile("(%s|%s|%s|%s)"% (re3, re2, re1, re4)).search (句子)
,我有
foo2 is a word, not bar2
foo2
bar2
据我所知,第一条规则被执行,但其他规则没有执行。 有人可以为我指出这个案例的正确方向吗?
亲切的问候,
最佳答案
您的示例存在各种问题:
- 您正在使用一个捕获 组,因此它获得您希望引用第一组内部正则表达式的索引
1
。请改用非捕获组(?:%s|%s|%s|%s)
。 即使在
|
内部,组索引也会增加。所以(?:(a)|(b)|(c))
你会得到:>>> re.match(r'(?:(a)|(b)|(c))', 'a').groups() ('a', None, None) >>> re.match(r'(?:(a)|(b)|(c))', 'b').groups() (None, 'b', None) >>> re.match(r'(?:(a)|(b)|(c))', 'c').groups() (None, None, 'c')
您似乎希望只有一个组 1 返回
a
、b
或c
,具体取决于分支。 .. 不,索引是按从左到右的顺序分配的,没有考虑正则表达式的语法。
regex
模块通过对组进行编号来完成您想要的操作。如果你想使用内置模块,你将不得不接受这样一个事实,即正则表达式的不同分支之间的编号是不一样的如果你使用命名组:
>>> import regex
>>> regex.match(r'(?:(?P<x>a)|(?P<x>b)|(?P<x>c))', 'a').groups()
('a',)
>>> regex.match(r'(?:(?P<x>a)|(?P<x>b)|(?P<x>c))', 'b').groups()
('b',)
>>> regex.match(r'(?:(?P<x>a)|(?P<x>b)|(?P<x>c))', 'c').groups()
('c',)
(尝试将正则表达式与 re
一起使用会导致重复组出错)。
关于python - 在 Python 中组合多个正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57672921/