9

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
xingbin
  • 25,716
  • 8
  • 51
  • 94
Kumar Harsh
  • 421
  • 5
  • 21

5 Answers5

9

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

Try using replace which doesnt use regex

String str2 = str1.replace("^", "\"");
Reimeus
  • 155,977
  • 14
  • 207
  • 269
3

^ means start of a line in regex, you can add two \ before it:

 String str2= str1.replaceAll("\\^", "\"");

The first is used to escape for compiling, the second is used to escape for regex.

xingbin
  • 25,716
  • 8
  • 51
  • 94
2

Since String::replaceAll consumes regular expression you need to convert your search and replacement strings into regular expressions first:

str.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("^"));
Hulk
  • 5,890
  • 1
  • 28
  • 50
jukzi
  • 974
  • 5
  • 14
0

Why do you want to use replaceAll. Is there any specific reason ? If you can use replace function then try below String str2= str1.replace("^", "\"");

Ros5292
  • 1,211
  • 1
  • 13
  • 20