【问题标题】:Is there a way in python to apply a list of regex patterns that are stored in a list to a single string?python中有没有办法将存储在列表中的正则表达式模式列表应用于单个字符串?
【发布时间】:2010-10-03 15:14:24
【问题描述】:

我有一个正则表达式模式列表(存储在列表类型中),我想将其应用于字符串。

有没有人知道一个好方法:

  1. 将列表中的每个正则表达式模式应用于字符串 和
  2. 如果匹配,则调用与列表中该模式关联的其他函数。

如果可能,我想在 python 中执行此操作

提前致谢。

【问题讨论】:

    标签: python regex list


    【解决方案1】:
    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的两个函数,因为两个模式都匹配。

    【讨论】:

    • 你甚至不需要列表(pats),只需使用'for pat in funcs'。
    • +1:很好,可读。 --- 但是跳过 pats 列表,只需迭代“for pat, func in funcs.items()”。
    • 次要问题:正则表达式不能以星号开头。
    • @Eli:如果您使用的是re.search,那么在这种情况下'.*' 是不必要的。
    • 嗯。为什么是字典,而不是元组列表?
    猜你喜欢
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    相关资源
    最近更新 更多