创建正则表达式匹配数组

新手上路,请多包涵

在 Java 中,我试图将所有正则表达式匹配返回到一个数组,但似乎你只能检查模式是否匹配某些东西(布尔值)。

如何使用正则表达式匹配来形成一个数组,其中包含与给定字符串中的正则表达式匹配的所有字符串?

原文由 Jake Sankey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 782
2 个回答

(如果您可以假设 Java >= 9,那么 4castle 的答案 比下面的要好)

您需要创建一个匹配器并使用它来迭代查找匹配项。

  import java.util.regex.Matcher;
 import java.util.regex.Pattern;

 ...

 List<String> allMatches = new ArrayList<String>();
 Matcher m = Pattern.compile("your regular expression here")
     .matcher(yourStringHere);
 while (m.find()) {
   allMatches.add(m.group());
 }

在此之后, allMatches 包含匹配项,如果你真的需要一个数组,你可以使用 allMatches.toArray(new String[0]) 来获取一个数组。


您还可以使用 MatchResult 编写辅助函数来循环匹配,因为 Matcher.toMatchResult() 返回当前组状态的快照。

例如你可以写一个懒惰的迭代器来让你做

for (MatchResult match : allMatches(pattern, input)) {
  // Use match, and maybe break without doing the work to find all possible matches.
}

通过做这样的事情:

 public static Iterable<MatchResult> allMatches(
      final Pattern p, final CharSequence input) {
  return new Iterable<MatchResult>() {
    public Iterator<MatchResult> iterator() {
      return new Iterator<MatchResult>() {
        // Use a matcher internally.
        final Matcher matcher = p.matcher(input);
        // Keep a match around that supports any interleaving of hasNext/next calls.
        MatchResult pending;

        public boolean hasNext() {
          // Lazily fill pending, and avoid calling find() multiple times if the
          // clients call hasNext() repeatedly before sampling via next().
          if (pending == null && matcher.find()) {
            pending = matcher.toMatchResult();
          }
          return pending != null;
        }

        public MatchResult next() {
          // Fill pending if necessary (as when clients call next() without
          // checking hasNext()), throw if not possible.
          if (!hasNext()) { throw new NoSuchElementException(); }
          // Consume pending so next call to hasNext() does a find().
          MatchResult next = pending;
          pending = null;
          return next;
        }

        /** Required to satisfy the interface, but unsupported. */
        public void remove() { throw new UnsupportedOperationException(); }
      };
    }
  };
}

有了这个,

 for (MatchResult match : allMatches(Pattern.compile("[abc]"), "abracadabra")) {
  System.out.println(match.group() + " at " + match.start());
}

产量

a at 0
b at 1
a at 3
c at 4
a at 5
a at 7
b at 8
a at 10

原文由 Mike Samuel 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 Java 9 中,您现在可以使用 Matcher#results() 获取 Stream<MatchResult> ,您可以使用它来获取匹配列表/数组。

 import java.util.regex.Pattern;
import java.util.regex.MatchResult;

 String[] matches = Pattern.compile("your regex here")
                          .matcher("string to search from here")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
                    // or .collect(Collectors.toList())

原文由 4castle 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题