Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 创建正则表达式匹配的数组_Java_Regex - Fatal编程技术网

Java 创建正则表达式匹配的数组

Java 创建正则表达式匹配的数组,java,regex,Java,Regex,在Java中,我试图将所有正则表达式匹配返回到一个数组,但似乎只能检查模式是否匹配某个对象(布尔值) 如何使用正则表达式匹配来形成与给定字符串中正则表达式匹配的所有字符串的数组?下面是一个简单的示例: Pattern pattern = Pattern.compile(regexPattern); List<String> list = new ArrayList<String>(); Matcher m = pattern.matcher(input); while (

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


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

下面是一个简单的示例:

Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
    list.add(m.group());
}
Pattern=Pattern.compile(regexpatern);
列表=新的ArrayList();
匹配器m=模式匹配器(输入);
while(m.find()){
list.add(m.group());
}

(如果您有更多的捕获组,您可以通过它们的索引将它们引用为group方法的参数。如果您需要数组,请使用
list.toArray()

以下是一个简单的示例:

Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
    list.add(m.group());
}
Pattern=Pattern.compile(regexpatern);
列表=新的ArrayList();
匹配器m=模式匹配器(输入);
while(m.find()){
list.add(m.group());
}
(如果您有更多的捕获组,您可以通过它们的索引将它们引用为group方法的参数。如果您需要数组,则使用
list.toArray()

(如果您可以假设Java>=9,则比下面的更好)

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

 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());
 }
通过这样做:

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

(如果可以假设Java>=9,则比下面的更好)

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

 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());
 }
通过这样做:

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

从:

使用
查找
并在数组/列表/任意位置插入生成的

来自:


使用
find
并将生成的
组插入数组/列表/任意位置。

Java使正则表达式过于复杂,并且不遵循perl风格。看一看如何在一行Java代码中实现这一点:

String[] matches = match("aa11bb22", "/(\\d+)/g" ); // => ["11", "22"]

Java使正则表达式过于复杂,而且它不遵循perl风格。看一看如何在一行Java代码中实现这一点:

String[] matches = match("aa11bb22", "/(\\d+)/g" ); // => ["11", "22"]
Set keyList=new HashSet();
Pattern regex=Pattern.compile(“\\{(.*?\\}”);
Matcher Matcher=regex.Matcher(“内容在这里”);
while(matcher.find()){
添加(匹配器组(1));
}
返回键列表;
Set keyList=new HashSet();
Pattern regex=Pattern.compile(“\\{(.*?\\}”);
Matcher Matcher=regex.Matcher(“内容在这里”);
while(matcher.find()){
添加(匹配器组(1));
}
返回键列表;

在Java 9中,您现在可以使用来获取匹配项列表/数组

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

在Java9中,您现在可以使用来获取匹配项,您可以使用它来获取匹配项的列表/数组

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

我不建议在这里使用ArrayList,因为您事先不知道大小,可能希望避免调整缓冲区的大小。相反,我更喜欢LinkedList——尽管这只是一个建议,不会让你的答案变得毫无根据。@Liv,花点时间对
ArrayList
LinkedList
进行基准测试,结果可能会令人惊讶。我听到了你的话,我知道这两种情况下的执行速度和内存占用;ArrayList的问题是,默认构造函数创建的容量为10——如果通过调用add()超过该大小,则必须承受内存分配和数组复制——这种情况可能会发生几次。当然,如果你只期望几场比赛,那么你的方法是更有效的;但是,如果您发现数组“调整大小”不止一次,我建议您使用LinkedList,如果您使用的是低延迟应用程序,则更是如此。@Liv,如果您的模式倾向于生成具有相当可预测大小的匹配,这取决于模式匹配的稀疏性还是密集性(基于
allMatches
vs
yourStringHere.length()
的长度总和)在我的经验中,
LinkedList
内存和迭代效率方面的成本通常是不值得的,因此
LinkedList
不是我的默认姿态。但是在优化热点时,交换列表实现以查看是否获得improvement.在Java9中,您现在可以使用来获取一个
,您可以使用它来生成一个数组(请参阅)。我不建议在此处使用ArrayList,因为您事先不知道其大小,并且可能希望避免缓冲区大小的调整。相反,我更喜欢LinkedList——尽管这只是一个建议,不会降低您的答案的有效性。@Liv,花点时间对
ArrayList
LinkedList
进行基准测试,结果如下所示可能会让人惊讶。我听到了你说的话,我知道这两种情况下的执行速度和内存占用;ArrayList的问题是默认构造函数创建的容量为10——如果调用add()超过该大小你将不得不忍受内存分配和数组复制——这种情况可能会发生几次。当然,如果你只期望几次匹配,那么你的方法是更有效的;但是如果你发现数组“正在调整大小”不止一次,我建议使用LinkedList,如果你正在处理一个低延迟的应用程序,则更是如此。@Liv,如果你的模式倾向于生成具有相当可预测大小的匹配,并且取决于模式匹配的稀疏性还是密集性(基于
allMatches
vs
yourStringHere.length()的长度之和)
)在我的经验中,
LinkedList
内存和迭代效率方面的成本通常是不值得的,因此
LinkedList
不是我的默认姿态。但是在优化热点时,交换列表实现以查看是否获得i在Java9中,您现在可以使用
String[] matches = Pattern.compile("your regex here")
                          .matcher("string to search from here")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
                    // or .collect(Collectors.toList())