【问题标题】:use regular expression in python to find two strings in line在python中使用正则表达式来查找两个字符串
【发布时间】:2014-09-17 11:07:14
【问题描述】:

我只需要知道如何在我的文件的一行中搜索两个字符串。

示例:我需要该行同时包含“protein_coding”和“exon”。 然后,如果它确实包含它们,我将打印每行的某些列。我知道如何打印它们,但不知道如何使用 reg ex 搜索两个字符串。 先感谢您。

这是正确的吗?: if re.match("protein_coding" & "exon" in line:

【问题讨论】:

标签: python regex


【解决方案1】:

此正则表达式将匹配同时具有“protein_coding”和“exon”字符串的行。

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

DEMO

>>> 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

【讨论】:

    【解决方案2】:

    使用锚点和前瞻断言:

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

    内联(?m) 修饰符启用多行模式。此处使用前瞻匹配两个子字符串,无论它们的顺序如何。

    Live Demo

    【讨论】:

      【解决方案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 
      

      【讨论】:

      • @dahlia:如果这有用,请考虑接受答案
      猜你喜欢
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 2012-05-19
      • 2021-06-01
      • 2010-12-24
      • 2016-05-16
      • 2014-07-28
      • 2015-06-21
      相关资源
      最近更新 更多