0

I want to replace all brackets in a String with the double quote character.

I thought this would work:

"[foo".replaceAll(Pattern.quote("["), Pattern.quote("""));

but it does not. Can anyone help me understand what I need to do?

5 Answers 5

5

You need to escape the quotes

"[foo".replaceAll(Pattern.quote("["), "\""); 
4
  • For some reason, this gives me: Q"Efoo istead of "foo. @JRaymond's approach gives "foo. Does it caused by the second Pattern.quote?
    – dragon66
    Apr 21, 2012 at 11:58
  • @dragon66 yes... the second argument is just supposed to be a plain replacement string, not a regular expression
    – JRaymond
    Apr 22, 2012 at 15:24
  • @JRaymond: +1 for confirming this. I am still wondering why this post seems to work for others but not me judging from the vote-ups.
    – dragon66
    Apr 22, 2012 at 16:17
  • @dragon66 Sorry guys, updated the answer. I'm also surprised it got 4 upvotes.
    – Ozzy
    Apr 22, 2012 at 21:15
5

replaceAll takes strings

"[foo".replaceAll("\\[", "\""));

Might I also add this as a good place to test your regex strings

1
  • you missed a backslash escaping Apr 20, 2012 at 22:46
1
"[foo".replaceAll(Pattern.quote("["), "\"") ;

The second argument - replacement - is a common string (doesnt need quotation).

1
"[foo".replaceAll("\\[", "\"")

to escape special characters in strings, like " \, you prepend a \, so \" becomes ", \\ becomes \, etc...

4
  • This does not work because [ is a meta-character in regexp patterns. You need to escape it to work. This is why the OP used Pattern.quote Apr 20, 2012 at 22:50
  • "[foo".replaceAll("\[", "\"")..?
    – Tor P
    Apr 20, 2012 at 23:10
  • hmm... if I do 2 \ then stackoverflow prints just 1 \, so the post didn't show what I was trying to communicate... lesson learned... :-p
    – Tor P
    Apr 20, 2012 at 23:14
  • You need to put 4 spaces in front of your code so that SO detects it is code and then it won't escape it Apr 20, 2012 at 23:16
0

The following works:

"[foo".replaceAll("\[", "\\"")

Notes:

  1. replaceAll interprets its first argument as a regular expression.
  2. you need to escape (within the regex context) the opening bracket or it will be malformed.
1
  • No it does not work because you must put 2 backlashes in front of the bracket Apr 20, 2012 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.