如何打印正则表达式模式未匹配的列号和行号。
我目前的代码:
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;
}
}
答案 0 :(得分:0)
您获得IllegalStateException
的原因是matcher.group()
或matcher.start()
。
很明显,如果控件转到else
块,则表示line
与Pattern
不匹配。如果找不到匹配项,您如何尝试打印该匹配项的start
或group
?
异常堆栈跟踪会清楚地说明: - 找不到匹配项。
如果您看到docs: -
抛出: IllegalStateException - 如果尚未尝试匹配,或者上一个匹配操作失败
在你的情况下,由于比赛失败,它会抛出IllegalStateException
。
正如您已经完成的那样,请保留matcher.group()
& matcher.start()
发表评论,取消注释count1++
,然后打印count1
。它会给你行号。
<强>更新: - 强>
将此作为else
阻止。
else {
count1++;
result = false;
System.out.println("**This line doesn't match the pattern*** "+line);
System.out.println("****problem at line number" + count1);
break;
}
答案 1 :(得分:0)
如果你想要展示不匹配的图案,那么你有两件事可以做。
1.创建正则表达式的相反模式,并在else块中匹配它并显示确切的单词。例如,如果你有一个像[aeiou]*
这样的正则表达式,那么对面就是[^aeiou]*
。
2.使用相同的变量保持matcher.start() and matcher.end()
并在else块中使用这些变量来查找发生不匹配的行的其余部分。假设你的结束20和循环的下一次迭代它来到了else阻止,这意味着在20之后没有匹配,所以在20之后显示行的内容。
编辑:
从流动代码中获取帮助
public static void main(String[] args) {
String source = "Java is best \n Test Java is good \n Java Hello";
Pattern pattern = Pattern.compile("Java");
Matcher matcher = null;
Scanner scanner = new Scanner(source);
String line = null;
int end = 0;
int lineNumber = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
matcher = pattern.matcher(line);
++lineNumber;
while (matcher.find()) {
System.out.println(matcher.group());
end = matcher.end();
}
if (end < line.length() - 1) {
System.out.println("NOt matched Line :" + lineNumber + " Words:-"
+ line.substring(end));
}
}
}