本文介绍了python中是否有一种方法可以将存储在列表中的正则表达式模式列表应用于单个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个正则表达式模式列表(以列表类型存储),我想将其应用于字符串.
i have a list of regex patterns (stored in a list type) that I would like to apply to a string.
有人知道一个好方法吗:
Does anyone know a good way to:
- 将列表中的每个正则表达式模式应用于字符串和
- 如果匹配,则调用与列表中的该模式关联的另一个函数.
- Apply every regex pattern in the list to the stringand
- Call a different function that is associated with that pattern in the list if it matches.
如果可能的话,我想在python中这样做
I would like to do this in python if possible
提前谢谢.
推荐答案
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
的两个函数,因为两个模式都匹配.
The above code will call both functions for the string s
because both patterns are matched.
这篇关于python中是否有一种方法可以将存储在列表中的正则表达式模式列表应用于单个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!