如何打印正则表达式模式不匹配的列号和行号。
我当前的代码:
reader = new BufferedReader(new FileReader(credentialPath));
Pattern pattern = Pattern
.compile(ApplicationLiterals.CREDENTIALS_URL_REG_EX);
String line;
while ((line = reader.readLine()) != null) {
Matcher matcher = pattern.matcher(line.trim());
if (matcher.find()) {
// System.out.println(matcher.group());
// System.out.println("**" + matcher.start());
// System.out.println("***" + matcher.end());
result = true;
count1++;
} else {
// count1++;
result = false;
// System.out.println(matcher.group());
// System.out.println(matcher.start());
System.out.println("****problem at line number" + count1);
break;
}
}
最佳答案
您收到 IllegalStateException
的原因是 matcher.group()
或 matcher.start()
。
很明显,如果控件转到 else
block ,则意味着 line
与 Pattern
不匹配。当没有找到匹配项时,如何尝试打印该匹配项的 start
或 group
?
异常堆栈跟踪将清楚地说明这一点:- 未找到匹配项。
如果您看到 docs :-
Throws: IllegalStateException - If no match has yet been attempted, or if the previous match operation failed
在您的情况下,由于匹配失败,它会抛出 IllegalStateException
。
正如您已经完成的那样,保留 matcher.group()
和 matcher.start()
注释,取消注释 count1++
和只需打印 count1
即可。它会给你行号。
更新:-
将此作为您的 else
block 。
else {
count1++;
result = false;
System.out.println("**This line doesn't match the pattern*** "+line);
System.out.println("****problem at line number" + count1);
break;
}
关于java - 如何打印模式不匹配的列号和行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15808251/