You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现针对任意字符串的Globbing列表模式匹配?

解决任意字符串的Globbing匹配需求

其实你不用找额外的工具——Python标准库中的fnmatch模块本身就可以处理任意字符串的Globbing匹配,它并不是只能用于文件路径匹配,这可能是你之前的误解~

直接用fnmatch.fnmatch()函数就能实现你想要的效果,举个例子:

import fnmatch

aa = ['a.b.*', 'a.b.x', '*']
target_str = 'a.b.c'

# 遍历模式列表,筛选出匹配的项
matching_patterns = [pattern for pattern in aa if fnmatch.fnmatch(target_str, pattern)]
print(matching_patterns)  # 输出: ['a.b.*', '*']

为什么fnmatch能行?

fnmatch实现的是shell风格的通配符匹配规则,核心就是处理字符串匹配,和文件系统完全无关:

  • * 匹配任意长度的任意字符(包括空字符串)
  • ? 匹配单个任意字符
  • [chars] 匹配括号内的任意单个字符
  • [!chars] 匹配不在括号内的任意单个字符

如果需要更灵活的扩展(比如结合正则的其他特性),还可以用fnmatch.translate()把Globbing模式转换成正则表达式,再用re模块进行匹配:

import fnmatch
import re

aa = ['a.b.*', 'a.b.x', '*']
target_str = 'a.b.c'

matching_patterns = []
for pattern in aa:
    # 把Globbing模式转成正则表达式
    regex_pattern = fnmatch.translate(pattern)
    # 用fullmatch确保整个字符串匹配
    if re.fullmatch(regex_pattern, target_str):
        matching_patterns.append(pattern)

print(matching_patterns)  # 同样输出: ['a.b.*', '*']

至于glob模块,它确实是用来扫描文件系统路径的,但底层其实也是依赖fnmatch的匹配逻辑。所以针对你的任意字符串匹配需求,直接用fnmatch就足够了。

内容的提问来源于stack exchange,提问作者Ray Salemi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:22:31