gpt4 book ai didi

java - 我想使用 StringTokenizer 搜索字符串,但我要查找的字符串中有一个分隔符 - Java

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:48 25 4
gpt4 key购买 nike

我有一个名为 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" 但它不起作用,因为撇号是分隔符。如果我删除该分隔符,那么我将无法搜索 "involvement""commitment""involved"“committed” 在第 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";
}

关于java - 我想使用 StringTokenizer 搜索字符串,但我要查找的字符串中有一个分隔符 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8813779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com