Java 匹配器甚至不匹配循环中的 find()

标签 java regex matcher

简介

我想在 Java 中使用 RegEx 提取字符串中的子字符串。为此,让我们使用 Pattern 和 Matcher 类来正确地完成它。

代码

package stringlearning;

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

/**
 *
 * @author Jonathan
 */
public class StringLearning {

    //Example String
    public static String line = "This is the (first|second|third) choice.";


    public static void main(String[] args) 
    {

        //String is right, right?
        System.out.println("Line is: " + line);

        //How to use RegEx in Java properly
        Pattern pattern = Pattern.compile("\\(([^\\)]+)\\)", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(line);

        //While we find, keep looping
        while(matcher.find())
        {
            //What we foud out?
            System.out.println(matcher.matches());
            System.out.println(matcher.groupCount());
            System.out.println(matcher.group(1));
        }



    }

}

问题

我还是不明白为什么它找不到任何东西。正则表达式是在 RegEx 上创建的并在那里正常工作(不要忘记转义!'/')

我想知道我错过了什么不匹配

注意事项

  • 集成开发环境:NetBeans
  • Java 版本为 1.8.0_221

最佳答案

问题出在 while 循环中的这一行:

System.out.println(matcher.matches());

此处 matches() 尝试将整个区域与模式匹配。

如果匹配成功,则可以通过startendgroup 方法获取更多信息。

由于您的正则表达式不匹配整个输入,matches() 返回 false 并且您将得到 java.lang.IllegalStateException where code调用 .group(1)

要修复,只需注释掉 System.out.println(matcher.matches()); 行并重新运行代码。

顺便说一句,你可以使用这个更短的正则表达式:

final Pattern pattern = Pattern.compile("\\(([^)]+)\\)");

因为不需要在字符类中转义 ) 并且 DOTALL 在这里是多余的,因为您没有在正则表达式中的任何地方使用 DOT。

关于Java 匹配器甚至不匹配循环中的 find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57793416/

相关文章:

java - 我的返回值返回错误

java - 如何查询默认的 SpeechRecognizer

regex - perl:用不同大小的图案替换图案

.net - 正则表达式头痛

java - 模式java : 2 caracters less than n times and their sum of appereance less n too

java - 从 Google Cloud Storage 流式传输文件

java - Socket 的 PrintWriter 在关闭之前不会发送

regex - 从 CMake 中的 REGEX REPLACE 中排除包含特定字符串的行

junit - Hamcrest - Matchers.hasProperty : how to check if a List of objects contains an object with a concrete value

scala - 如何在 Specs2 (Scala) 中显示自定义失败消息?