如何在Java中使用正则表达式删除字符串中的反斜杠?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2242417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove the backslash in string using regex in Java?
提问by zahir hussain
How to remove the backslash in string using regex in Java?
如何在Java中使用正则表达式删除字符串中的反斜杠?
For example:
例如:
hai how are\ you?
I want only:
我只想:
hai how are you?
采纳答案by Alan Moore
str = str.replaceAll("\\", "");
or
或者
str = str.replace("\", "");
replaceAll()
treats the first argument as a regex, so you have to double escape the backslash. replace()
treats it as a literal string, so you only have to escape it once.
replaceAll()
将第一个参数视为正则表达式,因此您必须对反斜杠进行双重转义。 replace()
将其视为文字字符串,因此您只需将其转义一次。
回答by Mark Elliot
You can simply use String.replaceAll()
您可以简单地使用String.replaceAll()
String foo = "hai how are\ you?";
String bar = foo.replaceAll("\\", "");
回答by Abhiram
String foo = "hai how are\ you?"; String bar = foo.replaceAll("\\", ""); Doesnt work java.util.regex.PatternSyntaxException occurs.... Find out the reason!! @Alan has already answered.. good
String foo = "你好吗\你?"; String bar = foo.replaceAll("\\", ""); 不工作 java.util.regex.PatternSyntaxException 发生....找出原因!@Alan 已经回答了.. 好
String bar = foo.replace("\\", ""); Does work
String bar = foo.replace("\\", ""); 有效