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 
0

5 Answers 5

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("\\^", "\""); 
Sign up to request clarification or add additional context in comments.

6 Comments

Then how can i print the output i want
Yes: use replace instead of replaceAll
@MauricePerry String str2= str1.replaceAll("\\^", "\""); should works you will "escape" ^ but `` need to be also escaped :D
@xxxvodnikxxx so would String str2 = str1.replace("^", "\""); and it's simpler
For this case will work also replace instead replace all, but ofc if you will want really to replace all in string, I mean if there will be more occurrence, then you can use it.. As obviously method name says.
|
4

Try using replace which doesnt use regex

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

1 Comment

or, similar char based replace('^','"') Both have better performance than regex versions
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.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.