我从其他程序收到消息,其中某些字符已更改:
\n
(输入)-> #
(哈希)#
-> \#
\
-> \\\\
当我尝试用我的代码逆转这些更改时,它不起作用,可能是这样
Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.
这是我的代码:
public String changeChars(final String message) {
String changedMessage = message;
changedMessage = changePattern(changedMessage, "[^\\\\][#]", "\n");
changedMessage = changePattern(changedMessage, "([^\\\\][\\\\#])", "#");
changedMessage = changePattern(changedMessage, "[\\\\\\\\\\\\\\\\]", "\\\\");
return changedMessage;
}
private String changePattern(final String message, String patternString, String replaceString) {
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(message);
return matcher.replaceAll(replaceString);
}
最佳答案
我假设你的编码方法是这样工作的。
- 全部替换
\
与\\\\
- 标记最初放置的
#
如\#
- 现在我们知道所有最初放置的
#
有\
在它之前我们可以用它来标记新行\n
与#
.
代码可能类似于
data = data.replace("\\", "\\\\\\\\");
data = data.replace("#", "\\#");
data = data.replace("\n", "#");
要反转此操作,我们需要从末尾开始(形成最后一个替换)
- 我们将替换所有
#
没有\
在它之前换行\n
标记(如果我们从第二个替换\#
->#
开始,我们稍后将不知道#
中的哪个替换了\n
)。 - 之后我们就可以安全地替换
\#
与#
(这样我们就可以去掉原始字符串中不存在的额外\
,并且不会影响我们最后的替换步骤)。 - 最后我们替换
\\\\
与\
.
我们可以这样做。
//your previous regex [^\\\\][#] describes "any character that is not \ and #
//but since we don't want to include that additional non `\` mark while replacing
//we should use negative look-behind mechanism "(?<!prefix)"
data = data.replaceAll("(?<!\\\\)#", "\n");
//now since we got rid of additional "#" its time to replace `\#` to `#`
data = data.replace("\\#", "#");
//and lastly `\\\\` to `\`
data = data.replace("\\\\\\\\", "\\");
关于java - 不能使用/(斜杠)执行 matcher.replaceAll(...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14113790/