java - JAVA中如何去除字符串中的转义字符

标签 java regex

我有像 "\\{\\{\\{testing}}}" 这样的输入字符串,我想删除所有 "\"。所需的 o/p:“{{{testing}}}”

我正在使用以下代码来完成此任务。

protected String removeEscapeChars(String regex, String remainingValue) {
    Matcher matcher = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(remainingValue);
    while (matcher.find()) {
        String before = remainingValue.substring(0, matcher.start());
        String after = remainingValue.substring(matcher.start() + 1);
        remainingValue = (before + after);
    }
    return remainingValue;
}

我将正则表达式作为 "\\\\{.*?\\\\}" 传递。

代码仅对第一次出现的“\{”工作正常,但并非对所有出现的情况都有效。 查看不同输入的以下输出。

  1. i/p : "\\{testing}" - o/p: "{testing}"
  2. i/p : "\\{\\{testing}}" - o/p: "{\\{testing}}"
  3. i/p : "\\{\\{\\{testing}}}" - o/p: "{\\{\\{testing}}}"

我希望"\"应该从传递的i/p字符串中移除,并且所有"\\{"应该替换为"{"

我觉得问题在于正则表达式值,即 "\\\\{.*?\\\\}"

任何人都可以让我知道获取所需 o/p 的正则表达式值应该是多少。

最佳答案

您不简单地使用 String#replace 的任何原因?

String noSlashes = input.replace("\\", "");

或者,如果您只需要在打开花括号之前删除反斜杠:

String noSlashes = input.replace("\\{", "{");

关于java - JAVA中如何去除字符串中的转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12423071/

相关文章:

java - Google App Engine 模块可以像 Maven 模块一样共享源代码吗?

Java : Method return

java - 调试期间无法查看来自 Java 源的变量值

regex - 如何匹配彼此相邻的括号?

regex - 如何在 powershell 中替换为评估代码?

java - Xamarin .jar 绑定(bind) - 'Bitmap could not be found'

java - main 方法的奇怪行为

python - 如何使用 re.sub 来实际替换文件名?

php - 使用正则表达式管理电话号码验证漏洞

c# - 正则表达式和管道运算符