我尝试使用正则表达式删除文本文件中的特定行,但收到非法状态异常。我最近试图习惯正则表达式并尝试使用 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/