替换具有反斜杠的变量

问题描述 投票:1回答:1

代码的目的是用配置文件的另一个值替换值。

旧值分配给变量oldValue =“serverip = http://82.347.34.12”

新值被分配给另一个变量newValue =“serverip = http://99.347.34.12”

void searchFile(File nameOfFile, String oldValue, String newValue) throws IOException {
    try {

                System.out.println("Old setting: " + lines); // returns -> serverip=http:\/\/82.347.34.12
                System.out.println("New setting: " + settingToApply); // returns --> serverip=http:\/\/99.347.34.12

                Path path = Paths.get(SETTINGS);
                Charset charset = StandardCharsets.UTF_8;

                String content = new String(Files.readAllBytes(path), charset);

                // changes any cases correctly except when value have \
                content = content.replaceAll(oldValue, newValue); 
                Files.write(path, content.getBytes(charset));

        }

        scanner.close();
    } catch (FileNotFoundException e) {
        // handle this
    }
}

}

谢谢。

java regex replace backslash
1个回答
1
投票

String.replaceAll采取Regular Expression。您将要么必须转义正则表达式特殊字符(例如斜杠)或使用String.replace,它不使用正则表达式。

© www.soinside.com 2019 - 2024. All rights reserved.