簡體   English   中英

“而不是重新研究”多個條件

[英]“and not re.search” multiple conditions

我正在處理一個python腳本,但遇到一種我無法弄清的情況。 在這一部分中,我打開了一個文件,最初定位的是以>開頭的行。 但是,我想跳過那些具有以下正則表達式模式的行:

uce.+$
ENSOFAS.+$
_[AB]_[0-9]+$
_[AB]_[0-9]+_rc$

如果我的代碼如下所示,僅針對其中之一,則可以正常工作:

with open(company_fn, "r") as company_fh:
    for line in company_fh:
        if line.startswith('>') and not re.search('uce.+$', line.strip()):
            print line

但是我也需要考慮其他所有可能性。 我試過了... not re.search(('uce.+$ | ENSOFAS.+$'), line.strip()): not re.search(('uce.+$' | 'ENSOFAS.+$'), line.strip()):和其他變體均未成功。 如何讓re.search考慮所有四個可能的正則表達式?

這是錯誤的:

not re.search(('uce.+$ | ENSOFAS.+$'), line.strip())

將正則表達式一起使用時,請勿添加“為了清楚起見的空間”,因為它們已被考慮在內。 這樣可行:

not re.search('uce.+$|ENSOFAS.+$',line.strip())

如果您能夠使用更新的regex模塊, regex可以定義如下異常:

import regex as re

string = """
uce123
ENSOFAS123
_A_123
_B_123_rc
this line should be matched
"""

exceptions = [r'uce.+$', r'ENSOFAS.+$', r'_[AB]_[0-9]+$', r'_[AB]_[0-9]+_rc$']

rx = re.compile(r'(?:{})(*SKIP)(*FAIL)|(.+)'.format("|".join(exceptions)), re.MULTILINE)

lines = rx.findall(string)
print(lines)
# ['this line should be matched']

本質上,這設置了一個數組exceptions ,該exceptions隨后會在整個表達式中加入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM