![](/img/trans.png)
[英]python regular expression to find something in between two strings or phrases
[英]use regular expression in python to find two strings in line
我只需要知道如何在文件的一行中搜索兩個字符串。
示例:我需要在行中同時包含“ protein_coding”和“ exon”。 然后,如果確實包含它們,我將打印每行的某些列。 我知道如何打印它們,但無法弄清楚如何使用正則表達式搜索兩個字符串。 先感謝您。
這是正確的嗎?:如果在行re.match(“ protein_coding”&“ exon”:
此正則表達式將匹配同時具有“ 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
如果測試字符串不要求使用正則表達式的,記得你可以使用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
使用錨點和超前斷言:
>>> re.findall(r'(?m)^(?=.*protein_coding)(?=.*exon).+$', data)
內聯(?m)
修飾符啟用多行模式。 在這里使用lookahead會匹配兩個子字符串,而不管它們的順序如何。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.