不区分大小写地使用Regexes,并使用单词边界查找“ the”的所有实例和变体。
indexOf("the")无法区分 “ the” 和 “ then”, 因为它们均以“ the”开头。同样,“ the”位于 “anathema” 的中间。
为避免这种情况,请使用正则表达式并搜索“ the”,并
b在其两边带有单词边界()。使用单词边界,而不是在“”上分割,或者仅使用
indexOf("the ")找不到 “ the”的 (两边的空格) 。 以及标点符号旁边的其他实例。您也可以不区分大小写地搜索 “ The” 。Pattern p = Pattern.compile("\bthe\b", Pattern.CASE_INSENSITIVE);while ( (line = bf.readLine()) != null) { linecount++; Matcher m = p.matcher(line); // indicate all matches on the line while (m.find()) { System.out.println("Word was found at position " + m.start() + " on line " + linecount); }}


