Java Pattern.CASE\u不区分大小写
我正在研究一个方法,该方法接受字符串参数,在文件中搜索该单词,并返回该单词的出现次数计数。我正在使用Java正则表达式模式和Matcher类和方法。我实现Pattern.CASE_INSENSITIVE的方式似乎无法正常工作。它仍然在区分大小写的基础上匹配Java Pattern.CASE\u不区分大小写,java,regex,Java,Regex,我正在研究一个方法,该方法接受字符串参数,在文件中搜索该单词,并返回该单词的出现次数计数。我正在使用Java正则表达式模式和Matcher类和方法。我实现Pattern.CASE_INSENSITIVE的方式似乎无法正常工作。它仍然在区分大小写的基础上匹配 public int lookup(String wrd) throws IOException, FileNotFoundException, { int cnt = 0; BufferedReader in =
public int lookup(String wrd) throws IOException, FileNotFoundException,
{
int cnt = 0;
BufferedReader in = new BufferedReader(new FileReader(this.filename));
String line = in.readLine();
while (line != null)
{
Pattern ptn = Pattern.compile(wrd, Pattern.CASE_INSENSITIVE);
Matcher mtch = ptn.mtch(line);
if (mtch.find()) {cnt++;}
line = input.readLine();
}
return cnt;
}
您没有滚动文件中的行,只读取第一行。没有理由使用正则表达式,对于大多数语言,您可以将
toLowerCase()
与indexOf()
组合使用,以获得不区分大小写的位置检查
public static void main(String[] args) throws Exception {
Path p = ...
String wrd = ...
System.out.println(totalMatches(p, wrd));
}
private static int totalMatches(Path path, String word) throws IOException {
try (BufferedReader reader = Files.newBufferedReader(path)) {
return reader.lines()
.mapToInt(l -> lineMatches(l, word))
.sum();
}
}
private static int lineMatches(String line, String word) {
int counter = 0, i = 0, found;
while ((found = line.toLowerCase().indexOf(word.toLowerCase(), i)) >= 0) {
counter++;
i = found + 1;
}
return counter;
}
正如我在评论中提到的,修复错误。这里是您的代码的一个修改和固定版本。这样看来,一切都是可行的:
public static int lookup(String wrd) throws IOException {
int cnt = 0;
BufferedReader in = new BufferedReader(
new StringReader(new String("word adfasdword avcasf\n asdf WoRd asdfWORDasdf")));
String line = in.readLine();
while (line != null) {
Pattern ptn = Pattern.compile(wrd, Pattern.CASE_INSENSITIVE);
Matcher mtch = ptn.matcher(line);
while (mtch.find()) {
cnt++;
}
line = in.readLine();
}
return cnt;
}
public static void main(String[] args) throws IOException {
System.out.println(lookup("WORD"));
System.out.println(lookup("word"));
System.out.println(lookup("WorD"));
System.out.println(lookup("worLd"));
}
输出:
4
4
4
0
你能给我们看一些输入数据样本吗?模式和正在读取的文件的(一小部分)?您的代码中有一大堆奇怪的错误。什么是
input
这里line=input.readLine()代码>。这是什么方法ptn.mtch(line)
,java.util.regex.Pattern
具有matcher
方法。如果您希望所有出现的单词,那么您应该执行while(mtch.find())
而不是If(mtch.find())
。。。只要修复它,它可能会工作。谢谢-While(mtch.find())是我代码中的关键问题。我感谢你的帮助!