java - 在正则表达式中获取非法状态异常

标签 java illegalstateexception

我尝试使用正则表达式删除文本文件中的特定行,但收到​​非法状态异常。我最近试图习惯正则表达式并尝试使用 match.matches();但该解决方案对我不起作用。对我做错了什么有什么建议

try {
    BufferedReader br = new BufferedReader(new FileReader("TestFile.txt"));
    //System.out.println(br.toString());

    ArrayList<String> list = new ArrayList<String>();
    String line= br.readLine() ;

    while (br.readLine() != null ) {
        //System.out.println(line);
        //System.out.println("test1"); { 
        Pattern regex = Pattern.compile("[^\\s\"]+|\"[^\"]*\"");
        Matcher regexMatcher = regex.matcher(line);
        String match = regexMatcher.group();// here is where the illegalstateexception occurs
        match = removeLeadingChar(match, "\"");
        match = removeLeadingChar(match, "\"");
        list.add(match);    
    //  }

    //      br.close();
    System.out.println(br);

Exception in thread "main" java.lang.IllegalStateException: No match found at java.base/java.util.regex.Matcher.group(Unknown Source) at java.base/java.util.regex.Matcher.group(Unknown Source)

最佳答案

使用Matcher.find()方法查看正则表达式模式中是否存在匹配项。在 IDE(例如 IntelliJ)中调试 regexMatcher.find() 方法的结果

try {
    BufferedReader br = new BufferedReader(new FileReader("TestFile.txt"));
    ArrayList<String> list = new ArrayList<>();

    String line;

    // Assign one line read from the file to a variable
    while ((line = br.readLine()) != null) {
        System.out.println(line);
        Pattern regex = Pattern.compile("[^\\s\"]+|\"[^\"]*\"");
        Matcher regexMatcher = regex.matcher(line);

        // Returns true if a match is found for the regular expression pattern.
        while (regexMatcher.find()) {
            String match = regexMatcher.group();
            match = removeLeadingChar(match, "\"");
            match = removeLeadingChar(match, "\"");
            list.add(match);
        }
    }

    // What is the purpose of this code?
    System.out.println(br);

    // If you want to output the string elements of the list
    System.out.println(list.toString());

    // must be closed after use.(to prevent memory leak)
    br.close();
} catch (IOException e) {
    // exception handling
    e.printStackTrace();
}

关于java - 在正则表达式中获取非法状态异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56095571/

相关文章:

Java - 标记为私有(private)的字段仍然可以在主函数中更改吗?

java - Spring:在 Java 配置中定义自定义 @Transactional 行为

java - 无法加载资源,总是返回null

java - 我看到 "Re-entry is not allowed"是什么意思?

java - 线程等待时出现大量 IllegalMonitorStateException

java - Presto集群+如何根据内存资源调优jvm.config

java - Nashorn 的 Object.bindProperties() 方法

java - 周期性写入数据时随机长IO暂停

java - 用户第二次启动线程时出现 IllegalStateException