首页 文章

Java Regex:匹配多个Occurences

提问于
浏览
2

我有一个电话号码列表和其他文本,如下所示:

+1-703-535-1039  +1-703-728-8382 +1-703-638-1039  +1-703-535-1039

我试图只匹配区号和数字的前3位数 .

目前我正在使用以下正则表达式:

\d{3}-\d{3}

但它只返回第一场比赛而不是所有比赛 .

请参阅此链接以供参考:

https://regex101.com/r/oO1lI9/1

1 回答

  • 1

    在regex101中,使用全局 g 标志来获取 all 匹配

    Demo

    要获得Java中的所有匹配:

    Pattern pattern = Pattern.compile("(\d{3}-\d{3})");
    Matcher matcher = pattern.matcher("+1-703-535-1039  +1-703-728-8382 +1-703-638-1039  +1-703-535-1039");
    
    // Find all matches
    while (matcher.find()) {
        // Get the matching string
        String match = matcher.group();
    }
    

    Reference

相关问题