Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace "\'" with any other character with String's replace()

I can't do a simple operation with String, replace \' with *.

Example: t'est\' -> t'est*

I have tried with replace and replaceAll methods:

String s has the value: "t'est\'";

s.replaceAll("\'", "*"); -> result: t*est*
s.replaceAll("\\'", "*"); -> result: t*est*
s.replaceAll("\\\'", "*"); -> result: t*est*
s.replaceAll("\\\\'", "*"); -> result: t'est'

s.replace("\'", "*"); -> result: t'est'
s.replace("\\'", "*"); -> result: t'est'
s.replace("\\\'", "*"); -> result: t'est'
s.replace("\\\\'", "*"); -> result: t'est'

But I don't get the result t'est* in any case.

like image 490
user3057179 Avatar asked Feb 04 '14 09:02

user3057179


1 Answers

Are you sure of the value of s? ' isn't a meaningful escape character, so if you write String s = "t'est\'", the value of s will just be "t'est'". To include the additional \ character, you need to escape it by writing String s = "t'est\\'". Then, I think "\\\\'" would be the regular expression to use to find it.

like image 174
amalloy Avatar answered Sep 28 '22 01:09

amalloy