簡體   English   中英

使用 Python 匹配具有多個正則表達式的行

[英]Match a line with multiple regex using Python

有沒有辦法查看一行是否包含與一組正則表達式匹配的單詞? 如果我有[regex1, regex2, regex3] ,並且我想查看一行是否與其中任何一個匹配,我該怎么做? 現在,我正在使用re.findall(regex1, line) ,但它一次只匹配 1 個正則表達式。

您可以使用內置函數any (或all如果所有正則表達式必須匹配)和 Generator 表達式來循環遍歷所有正則表達式對象。

any (regex.match(line) for regex in [regex1, regex2, regex3])

(或any(re.match(regex_str, line) for regex in [regex_str1, regex_str2, regex_str2])如果正則表達式不是預編譯的正則表達式對象,當然)

盡管與將您的正則表達式組合在單個表達式中相比,這會效率低下 - 如果此代碼對時間或 CPU 至關重要,您應該嘗試使用特殊的| 正則表達式運算符來分隔原始表達式。 組合所有正則表達式的一種簡單方法是使用字符串“join”運算符:

re.match("|".join([regex_str1, regex_str2, regex_str2]) , line)

盡管如果原始表達式已經使用了| ,則在此表單上組合正則表達式可能會導致錯誤的表達式| 操作員。

試試這個新的正則表達式:(regex1)|(regex2)|(regex3)。 這將匹配包含 3 個正則表達式中的任何一個的行。

您可以遍歷正則表達式項並進行搜索。

regexList = [regex1, regex2, regex3]

line = 'line of data'
gotMatch = False
for regex in regexList:
    s = re.search(regex,line)
    if s:
         gotMatch = True
         break

if gotMatch:
    doSomething()
#quite new to python but had the same problem. made this to find all with multiple 
#regular #expressions.

    regex1 = r"your regex here"
    regex2 = r"your regex here"     
    regex3 = r"your regex here"
    regexList = [regex1, regex1, regex3]

    for x in regexList:
    if re.findall(x, your string):
        some_list = re.findall(x, your string)     
        for y in some_list:
            found_regex_list.append(y)#make a list to add them to.

暫無
暫無

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

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