如何在Java中使用正则表达式删除字符串中的反斜杠?

2022-09-01 00:52:14

如何在Java中使用正则表达式删除字符串中的反斜杠?

例如:

hai how are\ you?

我只想要:

hai how are you?

答案 1
str = str.replaceAll("\\\\", "");

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

replaceAll()将第一个参数视为正则表达式,因此您必须对反斜杠进行双重转义。 将其视为文字字符串,因此您只需转义一次。replace()


答案 2

你可以简单地使用 String.replaceAll()

 String foo = "hai how are\\ you?";
 String bar = foo.replaceAll("\\\\", "");