创建正则表达式匹配数组 [英] Create array of regex matches

查看:38
本文介绍了创建正则表达式匹配数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

(4castle 的回答比下面的要好如果你可以假设 Java >= 9)

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

 import java.util.regex.Matcher;导入 java.util.regex.Pattern;...列表<字符串>allMatches = new ArrayList();Matcher m = Pattern.compile("你的正则表达式在这里").matcher(yourStringHere);而(m.find()){allMatches.add(m.group());}

此后,allMatches 包含匹配项,如果您确实需要,可以使用 allMatches.toArray(new String[0]) 来获取数组.

<小时>

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

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

for (MatchResult match : allMatches(pattern, input)) {//使用匹配,可能会中断而不做查找所有可能匹配的工作.}

通过做这样的事情:

public static Iterable所有匹配(最终模式 p,最终 CharSequence 输入){返回新的 Iterable() {公共迭代器迭代器(){return new Iterator() {//在内部使用匹配器.最终匹配器 matcher = p.matcher(input);//保持一个匹配,支持 hasNext/next 调用的任何交错.匹配结果待定;公共布尔 hasNext() {//延迟填充pending,避免多次调用find()//客户端在通过 next() 采样之前重复调用 hasNext().if (pending == null && matcher.find()) {挂起 = matcher.toMatchResult();}返回待定 != null;}公共匹配结果下一个(){//如有必要,填充待处理(当​​客户端调用 next() 时没有//检查 hasNext()),如果不可能则抛出.if (!hasNext()) { throw new NoSuchElementException();}//消耗挂起所以下一次调用 hasNext() 会执行 find().下一个匹配结果 = 待定;待定 = 空;接下来返回;}/** 需要满足接口,但不支持.*/public void remove() { throw new UnsupportedOperationException();}};}};}

有了这个,

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

收益

<块引用>

a 在 0b 在 1一个在 3c 在 4一个在 5一个在 7b 8 点一个在 10

In Java, I am trying to return all regex matches to an array but it seems that you can only check whether the pattern matches something or not (boolean).

How can I use a regex match to form an array of all string matching a regex expression in a given string?

解决方案

(4castle's answer is better than the below if you can assume Java >= 9)

You need to create a matcher and use that to iteratively find matches.

 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());
 }

After this, allMatches contains the matches, and you can use allMatches.toArray(new String[0]) to get an array if you really need one.


You can also use MatchResult to write helper functions to loop over matches since Matcher.toMatchResult() returns a snapshot of the current group state.

For example you can write a lazy iterator to let you do

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

by doing something like this:

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(); }
      };
    }
  };
}

With this,

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

yields

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

这篇关于创建正则表达式匹配数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆