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

时间:2019-05-12 01:34:51

标签: 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);
  

线程“主”中的异常java.lang.IllegalStateException:找不到匹配项   在java.base / java.util.regex.Matcher.group中(未知源)   在java.base / java.util.regex.Matcher.group(未知来源)

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

您的while循环错误,因此导致该行为空,请尝试以下操作:

try {
    BufferedReader br = new BufferedReader(new FileReader("TestFile.txt"));

    ArrayList<String> list = new ArrayList<String>();
    String line;     // <--- FIXED

    while ((line = br.readLine()) != null) { // <--- FIXED
        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(list.toString());
}