简体   繁体   English

如何从Java中的字符串中删除\\“?

[英]how to remove \" from string in java?

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

I want sameerraj as out put i tried following but no luck. 我想要sameerraj ,我尝试跟随,但没有运气。

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

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

please help me out. 请帮帮我。

If you want to replace it using regex ,then you can use replaceAll 如果要使用regex替换它,则可以使用replaceAll

In order to replace " ,you need to use \\ to escape it,so it will be replaceAll("\\"", "") 为了替换" ,您需要使用\\进行转义,因此它将是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("\\\\\\\\", "") 为了替换\\ ,需要使用\\来进行自身转义,但是由于\\是正则表达式中的特殊字符,因此需要再次使用\\来对其进行转义,因此总共需要使用4 \\ ,即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 \\\\ . 如果要将"\\"sameer\\\\\\"raj\\"更改为"sameerraj""sameerraj"删除两个字符: \\"\\\\

The easiest way to remove them is with replace . 删除它们最简单的方法是用replace

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

You don't need replaceAll , because you don't need to use a regular expression. 您不需要replaceAll ,因为您不需要使用正则表达式。

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.) mp = mp.replace("\\"", "").replace("\\\\", "");由于这些函数返回一个字符串,因此它们的工作原理相同。)

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. replace()函数将替换所有出现的给定输入。 replaceAll() function is intended for Regex. replaceAll()函数适用于正则表达式。

You can read about the differences between replace() and replaceAll() here: Difference between String replace() and replaceAll() 您可以在此处阅读有关replace()replaceAll() 之间的区别的信息: 字符串replace()和replaceAll()之间的区别

That will give you output sameerraj 那会给你输出sameerraj

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

System.out.println(doe);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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