Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting " when trying to replace a character in string [duplicate]

I want to replace " from a string with ^.

String str = "hello \"there";
System.out.println(str);
String str1 = str.replaceAll("\"", "^");
System.out.println(str1);
String str2= str1.replaceAll("^", "\"");
System.out.println(str2);

and the output is :

hello "there
hello ^there
"hello ^there

why I am getting extra " in start of string and ^ in between string

I am expecting:

hello "there
like image 631
Kumar Harsh Avatar asked Mar 27 '18 13:03

Kumar Harsh


2 Answers

the replaceAll() method consume a regex for the 1st argument.

the ^ in String str2= str1.replaceAll("^", "\""); will match the starting position within the string. So if you want the ^ char, write \^

Hope this code can help:

String str2= str1.replaceAll("\\^", "\"");
like image 142
tonyhoan Avatar answered Oct 06 '22 12:10

tonyhoan


Try using replace which doesnt use regex

String str2 = str1.replace("^", "\"");
like image 22
Reimeus Avatar answered Oct 06 '22 14:10

Reimeus