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

Regex匹配停在首个匹配项,如何同时捕获'catwoman'和'superman'?

如何让正则捕获到所有匹配项(不止首个)

嘿,这个问题我太熟了!默认情况下正则表达式只会返回第一个匹配结果,要一次性捕获到catwoman和superman这两个目标,核心是开启全局匹配模式,不同编程语言或工具的实现方式略有不同,我给你整理了几个常用场景的解决方案:

  • JavaScript场景:
    在正则表达式末尾加上g标志(全局匹配),然后使用match()方法就能拿到所有匹配结果:

    const text = "I'm a fan of catwoman and superman";
    const regex = /catwoman|superman/g;
    const allMatches = text.match(regex);
    // allMatches 结果是 ["catwoman", "superman"]
    
  • Python场景:
    使用re模块的findall()方法,它会直接返回所有匹配项组成的列表;如果需要更灵活的处理(比如获取匹配位置),可以用finditer()返回迭代器:

    import re
    text = "I'm a fan of catwoman and superman"
    # 方法1:直接获取所有匹配结果
    all_matches = re.findall(r'catwoman|superman', text)
    # all_matches 结果是 ['catwoman', 'superman']
    
    # 方法2:迭代处理每个匹配项
    for match in re.finditer(r'catwoman|superman', text):
        print(match.group())  # 依次输出 catwoman、superman
    
  • Java场景:
    通过Matcher对象的find()方法循环遍历,每次调用find()会定位到下一个匹配项,再用group()获取内容:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class RegexExample {
        public static void main(String[] args) {
            String text = "I'm a fan of catwoman and superman";
            Pattern pattern = Pattern.compile("catwoman|superman");
            Matcher matcher = pattern.matcher(text);
            
            while (matcher.find()) {
                System.out.println(matcher.group());  // 依次输出 catwoman、superman
            }
        }
    }
    
  • 正则测试工具场景:
    如果你用的是在线正则测试器,记得勾选界面上的"Global"(全局匹配)选项,这样就能看到所有匹配结果了。

另外要注意:如果你的正则表达式包含捕获组,部分语言(比如Python)的findall()会优先返回捕获组的内容,这时可以把整个匹配目标用括号包裹成一个整体捕获组,或者使用非捕获组(?:...)来避免干扰。

内容的提问来源于stack exchange,提问作者a.awaji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:07:07