• Post Reply Bookmark Topic Watch Topic
  • New Topic

Replace " with ' in string  RSS feed

 
Jyotika Kapoor
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you looked at the string's replace() method?

Henry
 
Jyotika Kapoor
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ,

I tried but getting syntax error.


str.replaceAll("<it doesnt allow me to put " this here >" , "'") ;


Regards
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 55772
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 55772
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Henry. Youcan tell I don't use that particular regex often
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!