我有一个名为quotes.txt的外部文件,我将向您展示该文件的一些内容:
1 Everybody's always telling me one thing and out the other.
2 I love criticism just so long as it's unqualified praise.
3 The difference between 'involvement' and 'commitment' is like an eggs-and-ham
breakfast: the chicken was 'involved' - the pig was 'committed'.
我用过这个:StringTokenizer str = new StringTokenizer(line, " .'");
这是搜索的代码:
String line = "";
boolean wordFound = false;
while((line = bufRead.readLine()) != null) {
while(str.hasMoreTokens()) {
String next = str.nextToken();
if(next.equalsIgnoreCase(targetWord) {
wordFound = true;
output = line;
break;
}
}
if(wordFound) break;
else output = "Quote not found";
}
现在,我想在第1行和第2行中搜索字符串"Everybody's"
和"it's"
,但由于撇号是分隔符之一,因此无效。如果我删除了该分隔符,那么我将无法在第3行中搜索"involvement"
,"commitment"
,"involved"
和"committed"
。
我可以用这个问题做什么合适的代码?请帮助和谢谢。
答案 0 :(得分:3)
我建议使用正则表达式(the Pattern
class)而不是StringTokenizer
。例如:
final Pattern targetWordPattern =
Pattern.compile("\\b" + Pattern.quote(targetWord) + "\\b",
Pattern.CASE_INSENSITIVE);
String line = "";
boolean wordFound = false;
while((line = bufRead.readLine()) != null) {
if(targetWordPattern.matcher(line).find()) {
wordFound = true;
break;
}
else
output = "Quote not found";
}
答案 1 :(得分:1)
按空格进行标记,然后按“字符”进行修剪。