gpt4 book ai didi

java - 如何编辑文本文档中的特定单词?

转载 作者:行者123 更新时间:2023-12-01 09:16:23 24 4
gpt4 key购买 nike

到目前为止,我的代码仅编辑由回车符分隔的单词。如果我通过空格或逗号分隔单词,它们不会被替换。

E.G.如果我在一行上写“嘿”,在下一行写“嗨”。如果我愿意,我的代码可以替换它们。但是,如果我在一行上有“hey”,并且“hey”旁边用逗号分隔“hi”,则我的代码不会替换其中任何一个。

我的代码的目标是替换 .CSV 文件中的单词,但如果我的代码无法替换由逗号或空格分隔的单词,则它不起作用。

这是我的代码,按下按钮即可激活:

try{
// Input the file location into Path variable 'p'
Path p = Paths.get("test test.txt");
//Path p = Paths.get("tiger.csv");

//Read the whole file to a ArrayList
List<String> fileContent = new ArrayList<>(Files.readAllLines(p));

//Converting user input from editSerialField to a string
String strSerial = editSerialField.getText();
//Converting user input from editLocationField to a string
String strLocation = editLocationField.getText();

//This structure looks for a duplicate in the text file, if so, replaces it with the user input from editLocationField.
for (int i = 0; i < fileContent.size(); i++)
{
if (fileContent.get(i).equals(strSerial))
{
fileContent.set(i, strLocation);
break;
}

}

// write the new String with the replaced line OVER the same file
Files.write(p, fileContent);

}catch(IOException e)
{
e.printStackTrace();
}

如何编辑由逗号或空格分隔的单词?另外,如果我可以替换单词,无论它们是大写还是小写,那就太好了,我该如何执行此操作?

谢谢。

最佳答案

使用正则表达式:

fileContent.replaceAll(s -> s.replaceAll("(?i)\\b" + strSerial + "\\b", strLocation));

在搜索词的两端添加 \b(表示“单词边界”)意味着仅替换整个单词

添加 (?i) 表示“忽略大小写”。

关于java - 如何编辑文本文档中的特定单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40517489/

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