gpt4 book ai didi

Java 正则表达式 : How to search a text or a phrase in a large text

转载 作者:行者123 更新时间:2023-11-30 03:14:18 25 4
gpt4 key购买 nike

我有一个很大的文本文件,我需要在文件中逐行搜索单词或短语,并输出包含在其中找到的文本的行。

例如,示例文本为

地球没有形状,
你在哪里?

如果用户搜索thou单词,则唯一显示的行是

Where [art] thou?

如果用户搜索地球,则应显示第一行。

我尝试使用 contains 函数,但当仅搜索 thou 时,它也会显示 without

这是我的示例代码:

String[] verseList = TextIO.readFile("pentateuch.txt");
Scanner kbd = new Scanner(System.in);
int counter = 0;

for (int i = 0; i < verseList.length; i++) {
String[] data = verseList[i].split("\t");
String[] info3 = data[3].split(" ");
System.out.print("Search for: ");
String txtSearch = kbd.nextLine();
LinkedList<String> searchedList = new LinkedList<String>();
for (String bible : verseList){
if (bible.contains(txtSearch)){
searchedList.add(bible);
counter++;
}
}
if (searchedList.size() > 0){
for (String s : searchedList){
String[] searchedData = s.split("\t");
System.out.printf("%s - %s - %s - %s \n",searchedData[0], searchedData[1], searchedData[2], searchedData[3]);
}
}
System.out.print("Total: " + counter);

所以我正在考虑使用regex,但我不知道如何使用。有人可以帮忙吗?谢谢。

最佳答案

由于有时变量在边界位置具有非单词字符,因此您不能依赖 \b字边界。

在这种情况下,使用环视 (?<!\w) 更安全和(?!\w) ,即在 Java 中,类似于:

"(?<!\\w)" + searchedData[n] + "(?!\\w)"

关于Java 正则表达式 : How to search a text or a phrase in a large text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32994306/

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