代码之家  ›  专栏  ›  技术社区  ›  noah

使用正则表达式作为python“in”关键字的搜索字符串

  •  0
  • noah  · 技术社区  · 4 年前

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

    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 在我刚刚放的壳里 * 今天到此为止。

    我想做的是让str成为regx:

    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
    

    什么是一种干净快速的方式来实现这样的事情?

    1 回复  |  直到 4 年前
        1
  •  0
  •   noah    4 年前

    你需要在集合中循环,而不是简单的in调用。

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

    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多万个元素。

        2
  •  0
  •   rioV8    4 年前

    可以将 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')