我正在读取包含以下两行的文件:“hello hi”和“hii hey”。 每行的第一个字符串是正则表达式,第二个字符串是替换字符串,即 String.replaceAll("hello", "hi")。我应该遍历文件中的每一行,以用替换内容替换字符串中的正则表达式。然而有一个问题。处理过的字符不应再次被替换。
例如我有这个字符串:“helloi”。 第一行之后,我有“hii”。 在第二行之后,天真的方法会导致“hey”。
我想确保“hii”仍然保留为“hii”,因为它已经包含处理过的字符。
请注意,我用作示例的字符串(“helloi”)只是一个简单的字符串,实际的字符串会很大并且包含多行。
你如何实现它?
编辑:让我用一个例子来更清楚地解释我的情况。我有一个字符串“helloi hii”。在文件的第一行之后,我有“hii hii”。但在第二行之后,我会发出“hii hey”。第一个“hii”包含已处理的字符,因此不会被替换
最佳答案
我想每次调用String.replaceAll
时,您都应该将搜索和替换字符串插入到HashSet
中。在调用 String.replaceAll
之前,检查此 HashSet 中是否存在搜索和替换字符串。
仅当 HashSet 中不存在搜索字符串和替换字符串时,您才调用 String.replaceAll
。
// at start
Set<String> processed = new HashSet<String>();
// read file line by line and have this inside your file processing loop
if (!processed.contains(search) && !processed.contains(replacement)) {
String repl = line.replaceAll(search, replacement);
processed.add(search);
processed.add(replacement);
}
关于java - String.replaceAll()方法: how to make sure processed characters can never be replaced again,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341154/