开发者

Java String.replaceAll doesn't replace a quote with escaped quote

Having a hard time replacing a quote with an escaped quote. I have a string that has the value of 'Foo "bar" foobar', and I am trying to replace the quotes around bar with escaped quotes, and it isn't working. I am going crazy.

s=s.replaceAll("\"","\\\"");

I开发者_StackOverflow中文版 would expect s to have the value of 'foo \"bar\" foobar', but it doesn't. Any help?


replaceAll uses regular expressions - in which the backslash just escapes the next character, even in the replacement.

Use replace instead and it's fine... or you can double the backslash in the second argument if you want to use the regular expression form:

String after = before.replaceAll("\"", "\\\\\"");

This could be useful if you need to match the input using regular expressions, but I'd strongly recommend using the non-regex form unless you actually need regex behaviour.

Personally I think it was a mistake for methods in String to use regular expressions to start with - things like foo.split(".") which will split on every character rather than on periods, completely unexpectedly to the unwary developer.


Use s = s.replace("\"", "\\\"");, which is the non-regex version.


You need to escape both replace all arguments because they are regex!

@Test
public void testReplace() {
    assertEquals("foo\\\"bar\\\"",
                 "foo\"bar\"".replaceAll("\\\"", "\\\\\\\""));
}

So if you want to write " you need to escape the regex -> \" but because you are in java you need to escape the \ and " for java to, so you get \\\\". (that is the search parameter).

For the replace parameter you want to have \" -> in regex: \\\" -> in Java \\\\\\\"


s=s.replaceAll("\"","\\\\\"");

But you should really go with replace(...) as the others here advice.


Use;

s=s.replaceAll("\"","\\\\\"");


String str = "'Foo \"Bar\" Bar'";
System.out.println(str);        
System.out.println(str.replaceAll("\"", "\\\\\""));


please follow below program and use > s.replace("/"."//");

public class stringbackslash {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s="\";
        s=s.replace("\", "\\");
        System.out.println(s);

    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜