java - 不能使用/(斜杠)执行 matcher.replaceAll(...)

标签 java regex pattern-matching

我从其他程序收到消息,其中某些字符已更改:

\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);
}

最佳答案

我假设你的编码方法是这样工作的。

  1. 全部替换\\\\\
  2. 标记最初放置的#\#
  3. 现在我们知道所有最初放置的#\在它之前我们可以用它来标记新行 \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/

相关文章:

java - 检查颜色是否已在 Java 数组中

java - 如何修复Android Studio中的网络安全配置?

JavaScript 正则表达式来验证复杂的字符串

rust - 在比赛中使用ref和与非引用匹配之间是否有区别?

java - 如何使用 Java Regex 查找字符串中所有重复的字符序列?

java - 通过 Guice 注入(inject) Immutables 类

java - 如何在 EJB JPA 中合并两个日期

Python 正则表达式 : What's wrong with this?

c# - L={a^nb^m| n+m=k ,n,m>=0} 在 C# 中使用正则表达式

rust - 为什么在解构变量后无法调用方法,但直接访问该字段却可以调用方法?