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

时间:2016-11-09 23:04:32

标签: java csv arraylist replace

截至目前,我的代码只会在返回时将其编辑为单词。如果我通过空格或逗号分隔单词,它们就不会被替换。

E.G。如果我在一行上'嘿',在下一行'嗨'。如果我愿意,我的代码可以替换它们。但是,如果我在一行上“嘿”,并且“嗨”在“嘿”旁边用逗号隔开,我的代码也不会替换。

我的代码的目标是替换.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();
    }

如何编辑用逗号或空格分隔的单词?此外,如果我可以替换单词,无论它们是大写还是小写,它都会很简洁,我该怎么做呢?

谢谢。

2 个答案:

答案 0 :(得分:1)

参与正则表达式:

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

在搜索字词的两端添加\b(意为“字边界”)意味着只会替换整个字

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

答案 1 :(得分:0)

在您拥有以下内容的代码中:

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

我猜你真的是这个意思:

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

然后循环遍历每一行时,只需检查并查看每一行是否包含您感兴趣的内容。您也可以将每行分成单词,然后使用java 8流检查每个单词。

相关问题