簡體   English   中英

有沒有辦法在python中將列表中存儲的正則表達式模式列表應用到單個字符串中?

[英]Is there a way in python to apply a list of regex patterns that are stored in a list to a single string?

我有一個我想要應用於字符串的正則表達式模式列表(存儲在列表類型中)。

有誰知道一個好方法:

  1. 將列表中的每個正則表達式模式應用於字符串和
  2. 如果匹配,則調用與列表中該模式關聯的其他函數。

如果可能的話我想在python中這樣做

提前致謝。

import re

def func1(s):
    print s, "is a nice string"

def func2(s):
    print s, "is a bad string"

funcs = {
    r".*pat1.*": func1,
    r".*pat2.*": func2
}
s = "Some string with both pat1 and pat2"

for pat, func in funcs.items():
    if re.search(pat, s):
        func(s)

上面的代碼將調用字符串s兩個函數,因為兩個模式都匹配。

暫無
暫無

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

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