Search code examples
javaregexstringreplaceall

Getting " when trying to replace a character in string


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

Solution

  • 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("\\^", "\"");