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

Python中如何用通配符匹配指定数量单词的字符串?

实现指定单词数量的精细化通配符匹配

内置方案:用re库自定义匹配规则

Python内置的正则表达式库re可以轻松实现你的需求,只需将自定义通配符转换为对应的正则规则:

  • 用*表示单个单词,对应正则\w+
  • 用**表示两个单词,对应正则\w+ \w+
  • 更多星号以此类推,比如***对应三个单词

下面是封装好的匹配函数:

import re

def word_count_wildcard_match(pattern, target):
    # 按星号数量从多到少替换,避免规则冲突
    pattern = re.sub(r'\*\*\*', r'\w+ \w+ \w+', pattern)
    pattern = re.sub(r'\*\*', r'\w+ \w+', pattern)
    pattern = re.sub(r'\*', r'\w+', pattern)
    # 用^和$确保完全匹配整个字符串
    regex = f'^{pattern}$'
    return re.fullmatch(regex, target) is not None

# 测试示例
print(word_count_wildcard_match("the * cat", "the fat cat"))  # 输出 True
print(word_count_wildcard_match("the * cat", "the fluffy fat cat"))  # 输出 False
print(word_count_wildcard_match("the ** cat", "the fluffy fat cat"))  # 输出 True

第三方库方案

如果不想自己写正则转换,可以尝试pywildcard这类扩展通配符库,但这类库默认规则不一定完全贴合你的需求,通常还是自定义正则转换更灵活可控,无需额外安装依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:25:23