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
  • 27,410
  • 9
  • 53
  • 103
Kumar Harsh
  • 423
  • 5
  • 26

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("\\^", "\"");
hoan
  • 1,058
  • 8
  • 13
5

Try using replace which doesnt use regex

String str2 = str1.replace("^", "\"");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
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
  • 27,410
  • 9
  • 53
  • 103
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
  • 6,399
  • 1
  • 30
  • 52
jukzi
  • 984
  • 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("^", "\"");

Rmahajan
  • 1,311
  • 1
  • 14
  • 23