【发布时间】:2010-10-03 15:14:24
【问题描述】:
我有一个正则表达式模式列表(存储在列表类型中),我想将其应用于字符串。
有没有人知道一个好方法:
- 将列表中的每个正则表达式模式应用于字符串 和
- 如果匹配,则调用与列表中该模式关联的其他函数。
如果可能,我想在 python 中执行此操作
提前致谢。
【问题讨论】:
我有一个正则表达式模式列表(存储在列表类型中),我想将其应用于字符串。
有没有人知道一个好方法:
如果可能,我想在 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的两个函数,因为两个模式都匹配。
【讨论】:
re.search,那么在这种情况下'.*' 是不必要的。