简体   繁体   中英

How to remove all single slashes from a string while leaving double slashes intact

Say you have the following text in a file.:

word \  sum \"span class=\\"blahblah\\">java

If I were to put the text into a string and use the replace method as follows. :

String text = "word \\ sum \\\"span class=\\\\\"blahblah\\\\\">java";
text = text.replace("\\", "");
System.out.println(text);

Then String text would be printed as:

word   sum "span class="blahblah">java

However, I want the double slashes to remain intact. What would I change in order to only remove the single slashes while leaving the double slashes intact?

Desired output:

word   sum "span class=\\"blahblah\\">java

尝试这个

    text = text.replaceAll("(?<!\\\\)\\\\(?!\\\\)", "");
String text = "word \\ sum \\\"span class=\\\\\"blahblah\\\\\">java";
text = text.replace("\\\\", "#$%"); // replace '\\' by something unique
text = text.replace("\\", "");//remove the '\'
text = text.replace("#$%", "\\\\");//get '\\' back

Look up Regular Expression Lookahead and Lookbehind patterns.

http://www.regular-expressions.info/lookaround.html

Keep in mind that lookbehind does not work in Javascript.

This will remove one backslash from any odd length consecutive backslashes:

text.replaceAll("(?<!\\\\)(\\\\\\\\)*\\\\(?!\\\\)","$1")

So in the case of

text = "word \\ sum \\\"span class=\\\\\"blah\\\\\\\"blah\\\\\">java"

or when printed: word \\ sum \\"span class=\\\\"blah\\\\\\"blah\\\\">java , the result is:

word sum "span class=\\"blah\\"blah\\">java

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