在Python中使用正则表达式查找行中的两个字符串

0 投票
3 回答
4632 浏览
提问于 2025-04-18 14:45

我只想知道怎么在文件的一行中搜索两个字符串。

举个例子:我需要这一行同时包含“protein_coding”和“exon”。如果包含这两个字符串,我就会打印出每一行的某些列。我知道怎么打印这些列,但就是搞不清楚怎么用正则表达式搜索两个字符串。

这样写对吗?: if re.match("protein_coding" & "exon" in line:

3 个回答

1

使用锚点和前瞻断言:

>>> re.findall(r'(?m)^(?=.*protein_coding)(?=.*exon).+$', data)

这里的 (?m) 是一个内联的修改器,它可以让你在多行模式下工作。使用前瞻断言可以让你匹配到两个子字符串,不管它们的顺序是什么。

在线演示

3

这个正则表达式可以找到同时包含“protein_coding”和“exon”这两个字符串的行。

^.*?\bprotein_coding\b.*?\bexon\b.*$

演示

>>> import re
>>> data = """protein_coding exon foo bar
... foo
... protein_coding
... """
>>> m = re.findall(r'^.*?\bprotein_coding\b.*?\bexon\b.*$', data, re.M)
>>> for i in m:
...     print i
... 
protein_coding exon foo bar
3

如果测试的字符串不需要用到正则表达式,记得你可以使用Python的字符串函数和 in 来处理:

>>> line='protein_coding other stuff exon more stuff'
>>> "protein_coding" in line and "exon" in line
True

或者如果你想测试任意数量的单词,可以使用 all 和一个目标单词的元组来进行测试:

>>> line='protein_coding other stuff exon more stuff'
>>> all(s in line for s in ("protein_coding", "exon", "words"))
False
>>> all(s in line for s in ("protein_coding", "exon", "stuff"))
True

如果匹配的内容需要用到正则表达式,并且你想限制使用多个不相关的正则表达式,可以使用 all 和一个推导式来进行测试:

>>> p1=re.compile(r'\b[a-z]+_coding\b')
>>> p2=re.compile(r'\bexon\b')
>>> li=[p.search(line) for p in [p1, p2]]
>>> li
[<_sre.SRE_Match object at 0x10856d988>, <_sre.SRE_Match object at 0x10856d9f0>]
>>> all(e for e in li)
True 

撰写回答