【问题标题】:Using regex as search string for python's "in" keyword [duplicate]使用正则表达式作为python“in”关键字的搜索字符串[重复]
【发布时间】:2021-01-17 17:30:43
【问题描述】:

假设我有一个路径集字典:

my_dict['some_key'] = {'abc/hi/you','xyz/hi/you','jkl/hi/you'}

我想看看这个集合中是否出现了路径。如果我有完整的路径,我只需执行以下操作:

str = 'abc/hi/you'
if str in my_dict['some_key']:
    print(str)

但如果我不知道b 是介于a 和c 之间的内容怎么办。如果它可以是字面上的任何东西怎么办。如果我是 ls 在 shell 中,我只会输入 * 并收工。

我想要做的是让 str 成为一个正则表达式:

regx = '^a.*c/hi/you$' #just assume this is the ideal regex. Doesn't really matter.
if regx in my_dict['some_key']:
    print('abc/hi/you') #print the actual path, not the regx

什么是实现这种东西的简洁快速的方法?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您需要遍历集合而不是简单的调用。

    为了避免为示例设置整个集合字典,我将其抽象为简单的 my_set。

    import re
    my_set = {'abc/hi/you','xyz/hi/you','jkl/hi/you'}
    regx  = re.compile('^a.*c/hi/you$')
    for path in my_set:
        if regx.match(path):
            print(path)
    

    我选择编译而不是简单地 re.match(),因为该集合在实际实现中可能有 100 万多个元素。

    【讨论】:

    • 虽然需要打印实际路径而不是正则表达式会破坏if x in y: print(x) 的典型“公式”,但重要的是要注意这不会改变我认为不可能的事实甚至做if regx in y: print(regx)
    • 无需编译,re 使用的是最近使用的正则表达式字符串缓存
    • 为什么要在 1 分钟内回答自己的问题?并对答案发表评论?
    • 关于编译,我的印象是编译一次对于非常多的缓存检查来说会稍微快一些?也许我弄错了。此外,由于更广泛程序的性质(在问题中显示的内容之外),从 imo 的可读性角度编译更有意义。
    【解决方案2】:

    您可以继承set 类并实现a in b 运算符

    import re
    from collections import defaultdict
    
    class MySet(set):
      def __contains__(self, regexStr):
        regex = re.compile(regexStr)
        for e in self:
          if regex.match(e):
            return True
        return False
    
    my_dict = defaultdict(MySet)
    
    my_dict['some_key'].add('abc/hi/you')
    
    regx = '^a.*c/hi/you$'
    if regx in my_dict['some_key']:
        print('abc/hi/you')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多