| Author |
Replace " with ' in string
|
Jyotika Kapoor
Greenhorn
Joined: Apr 25, 2009
Posts: 19
|
|
Hi all,
Would be grateful if some one can help in understanding how to replace " with ' in a string.
Thanks in advance.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16687
|
|
Have you looked at the string's replace() method?
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Jyotika Kapoor
Greenhorn
Joined: Apr 25, 2009
Posts: 19
|
|
hi ,
I tried but getting syntax error.
str.replaceAll("<it doesnt allow me to put " this here >" , "'") ;
Regards
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16687
|
|
Jyotika Kapoor wrote:I tried but getting syntax error.
This is because a double quote has meaning in a Java String. If you want to use a quote as a quote in a java string literal, you will need to escape it -- with a backslash.
Henry
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32651
|
|
Henry Wong wrote:. . . you will need to escape it -- with a backslash.
Henry
And if you want a backslash you may have to escape it with a backslash. If " won't work try \" and if \" won't work try \\" and if \\" won't work try \\\"
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16687
|
|
Campbell Ritchie wrote:And if you want a backslash you may have to escape it with a backslash. If " won't work try \" and if \" won't work try \\" and if \\" won't work try \\\"
There is no need for trial and error. You just need to remember two things. First, the Java string literal does its parts first before passing it to the regex engine, so you just have to escape for regex first, then the Java string (working backwards).
Second, you just need to memorize what needs to be escaped for the regex and the string. For the regex, it is all the special characters. And for the string, it is basically the quote and the backslash. So... in this case, the double quote doesn't have special meaning for the regex, hence, no escape is necessary for the regex. It does have special meaning for the double quote, so you need to escape it, hence, just one backslash and a quote, and it should be fine.
Henry
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32651
|
|
Thanks, Henry. Youcan tell I don't use that particular regex often
|
 |
 |
I agree. Here's the link: jrebel
|
|
subject: Replace " with ' in string
|
|
|