Skip to main content
 首页 » 编程设计

python之具有通配符匹配的字符串

2025年05月04日35zhujiabin

我需要用简单的通配符匹配两个字符串:

"oh.my.*" 匹配 "*.my.life"、"oh.my.goodness" 和 "*.*.*",但不是 "in.my.house"

唯一的通配符是*,它代替任意字符的字符串(减去.)

我想到了使用 fnmatch,但它不接受文件名中的通配符。

我现在正在使用一些带有正则表达式的代码——我想越简单越好:

def notify(self, event, message): 
    events = [] 
    r = re.compile(event.replace('.','\.').replace('*','[^\.]+')) 
    for e in self._events: 
        if r.match(e): 
            events.append(e) 
        else: 
            if e.find('*')>-1: 
                r2 = re.compile(e.replace('.','\.').replace('*','[^\.]+')) 
                if r2.match(event): 
                    events.append(e) 
    for event in events: 
        for callback in self._events[event]: 
            callback(self, message) 

请您参考如下方法:

这应该适合你:

def is_match(a, b): 
    aa = a.split('.') 
    bb = b.split('.') 
    if len(aa) != len(bb): return False 
    for x, y in zip(aa, bb): 
        if not (x == y or x == '*' or y == '*'): return False 
    return True 

工作原理:

  • 首先在 . 上拆分输入。
  • 如果参数有不同数量的组件,则立即失败。
  • 否则遍历组件并检查是否相等。
  • 如果任一组件是 *,这也算作成功匹配。
  • 如果任何组件不匹配返回False,否则返回True。