Java正则表达式用新值替换值

标签 java regex

如何让正则表达式获取文件中 name = 后面的值,并替换它。 我有一个名为:“myfile.txt”的文件。

public static void main(String[] args)
    File TextFile = new File("C:\\text.txt");
    if (TextFile.exists()) {
        try {
            ReplaceWordInFile(TextFile, "haical", "arnanda");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private static void ReplaceWordInFile(File MyFile, String OldText, String NewText)
        throws IOException {

    File tempFile = File.createTempFile("filetemp", ".tmp");
    FileWriter fw = new FileWriter(tempFile);

    Reader fr = new FileReader(MyFile);
    BufferedReader br = new BufferedReader(fr);

    while (br.ready()) {
        fw.write(br.readLine().replaceAll(OldText, NewText) + "\n");
    }

    fw.close();
    br.close();
    fr.close();
    tempFile.renameTo(MyFile);
}

文件 C:\text.txt 的内容是:

name = haical
address = Michigan 48309, Amerika Serikat
age = 19
gender = male
activity = school
hoby = hiking, travel

如果我在第一行运行上面的程序,name = haical 将更改为 name = arnanda。

我的问题是 name 中的值不是 'haical' 而是另一个值,所以我想获取 name = blablabla 之后的值。

此外,有时语句 name = haical 不会保留其空格数并更改其位置。

稍后输出的内容示例为:

address = Michigan 48309, Amerika Serikat
name   =    haical  
age = 19
gender = male
activity = school
hoby = hiking, travel

所以它并不总是在第一行和 = 之后的一些空格,但它总是以 name = 开头。

提前致谢。

最佳答案

使用

....replaceAll("^name\\s*=\\s*" + YourNameVariableToReplace + "\\s*$", "name="+YourNameVariableToInsert)

替换字符串。如果名称可能包含 Regex-Control-Chars,您可能需要先转义名称。

关于Java正则表达式用新值替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14282097/

相关文章:

Java(openjdk版本 "1.8.0_151",linux)内存中有数百万条记录。经常添加和请求排序数据

JavaFX 2.0 窗口到托盘

javascript - 在 JavaScript 中拆分字符串的帮助

c# - 正则表达式获取具有特殊字符的单词

python - 正则表达式 Python - 从文本文件中绘制数据

java - 如何避免在 try 语句中设置变量

java.lang.OutOfMemory错误: Java heap space - while writing pdf to outputstream

java - 创建 DFS 迷宫时遇到问题

c++ - 如何将字符串转换为正则表达式文字

c# - 正则表达式不能按我的需要工作