简体   繁体   中英

how to remove \" from string in java?

String mp ="\"sameer\\\"raj\"";

I want sameerraj as out put i tried following but no luck.

mp = mp.replace("\"", "");

mp=mp.replaceAll("\\\\", "");

please help me out.

If you want to replace it using regex ,then you can use replaceAll

In order to replace " ,you need to use \\ to escape it,so it will be replaceAll("\\"", "")

In order to replace \\ ,you need to use \\ to escape itself,but since \\ is a special character in regex,you need to use \\ to escape it again,so need to use 4 \\ in total,which is replaceAll("\\\\\\\\", "")

System.out.println(mp.replaceAll("\\\\", "").replaceAll("\"", ""));

output:

sameerraj

If you want to change "\\"sameer\\\\\\"raj\\" to "sameerraj" , there are two characters you want to remove: \\" and \\\\ .

The easiest way to remove them is with replace .

mp = mp.replace("\"", "").replace("\\","");

You don't need replaceAll , because you don't need to use a regular expression.

To remove \\" you need to use escape characters for both of the characters.

Based on your example, this would do the trick:

String mp ="\"sameer\\\"raj\"";
mp = mp.replace("\"", "");
mp = mp.replace("\\", "");

( mp = mp.replace("\\"", "").replace("\\\\", ""); would work the same since these functions return a string.)

If you want to remove \\" as a sequental block, you would type:

mp = mp.replace("\\\"", "");

The function will search for a substrings of \\" and replace them with empty strings.

replace() function will replace all the occurrences of a given input. replaceAll() function is intended for Regex.

You can read about the differences between replace() and replaceAll() here: Difference between String replace() and replaceAll()

That will give you output sameerraj

String mp ="\"sameer\\\"raj\"";
String r = mp.replace("\\\"","");
String doe=r.replace("\"","");

System.out.println(doe);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM