如何在 Java 中获得多个正则表达式匹配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1266943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:52:16  来源:igfitidea点击:

How to get multiple regex matches in Java?

javaregexmultiple-matches

提问by ripper234

How can I find all substrings that match a regex in Java? (Similar to Regex.Matchesin .Net)

如何在 Java 中找到与正则表达式匹配的所有子字符串?(类似于.Net 中的Regex.Matches

回答by Aaron Digulla

Create a Matcher and use find()to position it on the next match.

创建一个匹配器并用于find()在下一场比赛中定位它。

回答by ripper234

Here is a code sample:

这是一个代码示例:

int countMatches(Pattern pattern, String str) {
  int matches = 0;
  Matcher matcher = pattern.matcher(str);
  while (matcher.find())
    matches++;
  return matches;
}