java - 创建正则表达式匹配数组

标签 java regex

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

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

最佳答案

(如果您可以假设 Java >= 9,4castle's answer 比下面的更好)

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

 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

关于java - 创建正则表达式匹配数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58778765/

相关文章:

html - RegEx 匹配打开的标签,XHTML 自包含标签除外

javascript - 由 DOS 创建的 CSV 不适用于我的 Regexp javascript

java - 土耳其 ("Asia/Istanbul"或 "Europe/Istanbul"上的 JDK 时区问题)

java - 想要使用 Spring Security 使用电子邮件或手机号码登录

java - 如何使用java在MySql WorkBench中插入DateTime?

c# - 用于删除 XML 标记及其内容的正则表达式

java - 删除两个字符之间的字符串

java - Netbeans 中是否存在缺少 JavaDoc 警告?

java - 如何在 Maven 中添加来自 Sonatype 快照的依赖项

php - WordPress 过滤器 - 将 "src"替换为 "load-src"