如何在JAVA中从字符串中删除转义字符

如何在JAVA中从字符串中删除转义字符,java,regex,Java,Regex,我有像“\\{\\{\{\{testing}}}”这样的输入字符串,我想删除所有“\”。所需的o/p:“{{{{testing}}}” 我使用下面的代码来实现这一点 protected String removeEscapeChars(String regex, String remainingValue) { Matcher matcher = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(remainingValue

我有像
“\\{\\{\{\{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;
}
我将正则表达式作为
“\\\\{.*?\\\\}”
传递

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

  • i/p:
    “\\{testing}”
    -o/p:
    “{testing}”
  • i/p:
    “\\{\\{testing}}”
    -o/p:
    “{\\{testing}}”
  • i/p:
    “\\{\\{\\{testing}}}”
    -o/p:
    “{\\{\\{testing}}}}”
  • 我希望从传递的I/p字符串中删除
    “\”
    ,并将所有
    “\\{”
    替换为
    “{

    我觉得问题出在regex值上,即,
    “\\\{.*.\\\\}”


    有人能告诉我获取所需o/p的正则表达式值应该是多少吗。

    有什么原因不能简单使用吗

    或者,如果只需要在打开花括号之前删除反斜杠,请执行以下操作:

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

    它应该简单如下:

    String result = remainingValue.replace("\\", "");
    

    正如前面所回答的,如果您只想删除
    {
    之前的斜杠
    \
    ,最好的方法就是使用

    String noSlashes = input.replace("\\{", "{");
    
    但是在你的问题中,你问过谁能告诉我正则表达式的值应该是多少。如果你使用正则表达式是因为你不想在任何
    {
    之前删除
    ,而只想在那些
    {
    之后用
    }
    正确关闭的
    {/code>,那么答案是:不。

    更改正则表达式:
    “\\&([^;]{6})”


    它应该可以工作。

    为什么不直接使用replaceAll(“\\”,”)您也可以添加其他字符…您是否作为输入传递
    “\{testing}”
    “\{testing}”
    ?最后一个不会编译。您的示例的输出是:
    i/p:“\{testing}”-o/p:“\testing}”
    i/p:“\{testing}”“-o/p:“\{testing}}”
    i/p:“\{\{\{testing}}}”-o/p:“\{{testing}}}}”
    也许我不理解你的问题,但在我看来,replaceAll可以做到。下面的示例将删除字符'\'、'.'和'/'replaceAll(“[\\\\]*[\]*[\]*[/]*”,“)我最后一次评论的输出与您所说的不同,是关于@Baz版本之前显示的正则表达式:
    “\\{.*.\}”
    ,以及当前正则表达式(
    “\\{.*.\\}”
    )您将获得一个
    PatternSyntaxException
    。该方法是泛型方法,我正在使用它来转义不同的字符。我将根据要删除的字符生成正则表达式值。这里我的代码仅适用于首次出现,不适用于其他情况。@user1073430我要说的是,您似乎正在重写一个已经存在的方法。您可以如果您想使用正则表达式,也可以使用
    replaceAll
    。您回答的问题是什么?这是Toto:):“如何在JAVA中从字符串中删除转义字符?”
    String noSlashes = input.replace("\\{", "{");
    
    private String removeEscapeChars(String remainingValue) {
            Matcher matcher = Pattern.compile("\\&([^;]{6})", 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;
        }