String.replaceAll(String regex, String replacement) question

  • Thread starter Mladen Adamovic
  • Start date
M

Mladen Adamovic

I tried to replace " with \".
s.replaceAll("[\"]",\\\"");
but it does nothing!!

I tried then
s.replaceAll("[\Q"\E]","\Q\"\E")
but I got five sintax error?!?!?!?

I'm using JDK 1.4.2_01.

What's wrong?
 
A

Alan Moore

I tried to replace all " with \".
s=s.replaceAll("[\"]","\\\"");
but it does nothing!! String remains the same!!!

I tried then
s=s.replaceAll("[\Q"\E]","\Q\"\E")
but I got five sintax error?!?!?!?

I'm using JDK 1.4.2_01.

What's wrong?

P.S. It was a typing error in first message I posted about this.

Actually, your first version does do something: it replaces every
double-quote with a double-quote. The first argument is okay
(although you don't need the square brackets), but the second argument
is short a couple of backslashes. See, first the Java compiler
processes the arguments, turning them into ["] and \". Then the
Matcher looks at that single backslash in the second argument, decides
it's only there to escape the double-quote, and throws it away. So
you need four backslashes to get one into the output, and one more to
escape the double-quote:

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

The \Q...\E construct won't help here, because both " and \ are
special to String literals, so they have to be escaped anyway. And
putting it inside a character class (square brackets), is at least
redundant, if not an error. And, most importantly, you only used one
backslash. If you want the Pattern compiler to "see" a single
backslash, you have to put two in the regex string. Except for
escaping double-quotes, backslashes should *always* appear in pairs in
a regex string, and you have to use four of them to actually match a
backslash.

Oh, and \Q...\E is totally meaningless in the replacement string.
 
M

Mladen Adamovic

See, first the Java compiler
processes the arguments, turning them into ["] and \". Then the
Matcher looks at that single backslash in the second argument, decides
it's only there to escape the double-quote, and throws it away.

Thanks for help Alan.
I really think that escape sequences shouldn't be processed TWICE when
program call
String.replaceAll(String regex, String replacement)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top