简体   繁体   English

Java代码替换包含算术运算符的文件中的单词

[英]Java code to replace a word in a file containing arithmetic operators

I have written a code that replaces only a particular word in a file. 我已经编写了仅替换文件中特定单词的代码。 The code works fine however if I want to replace a word containing an arithmetic operator in it the code doesn't work. 该代码工作正常,但是如果我想替换其中包含算术运算符的单词,则该代码将无法正常工作。 I have also tried to escape special characters but still, it doesn't work. 我也尝试过转义特殊字符,但仍然无法正常工作。 Here is the code: 这是代码:

public void replacePassword(String newPass, String oldPass, String destFile) throws IOException {

    Path filePath = Paths.get(destFile);
    String fileContent = new String(Files.readAllBytes(filePath));
    //System.out.println(fileContent);
    fileContent = fileContent.replaceAll(Matcher.quoteReplacement(oldPass), Matcher.quoteReplacement(newPass));
    //System.out.println(fileContent);
    Files.write(filePath, fileContent.getBytes());
}

Kindly help me in solving this problem. 请帮助我解决这个问题。

I think maybe you want to use method replace(target, replacement) and not replaceAll(regex, replacement). 我想也许您想使用方法replace(target,替换)而不是replaceAll(regex,替换)。 The difference between this two methods is that the second one expect regex. 这两种方法之间的区别在于,第二种方法使用正则表达式。 If you have luck and do not give any special character for the regex then it will be considered as string and work properly. 如果运气好的话,并且不给正则表达式指定任何特殊字符,那么它将被视为字符串并且可以正常工作。 That why you did not have problems before. 那就是为什么您以前没有问题。

So please just try to change the method with replace(target, replacement) and tell us if you still have a problem. 因此,请尝试使用replace(target,replace)更改方法,并告诉我们是否仍然存在问题。

Example: 例:

public void replacePassword(String newPass, String oldPass, String destFile) throws IOException
{

    Path filePath = Paths.get(destFile);
    String fileContent = new String(Files.readAllBytes(filePath));
    //System.out.println(fileContent);
    //Here you use replace method not replaceAll!
    fileContent = fileContent.replace(Matcher.quoteReplacement(oldPass), Matcher.quoteReplacement(newPass));
    //System.out.println(fileContent);
    Files.write(filePath, fileContent.getBytes());

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM