替换Java中的空格和其他字符

替换Java中的空格和其他字符,java,regex,string,replace,Java,Regex,String,Replace,为什么这个代码不起作用 public static void main(String[] args) { String s = "You need the new version for this. Please update app ..."; System.out.println(s.replaceAll(". ", ".\\\\n").replaceAll(" ...", "...")); } 这是我想要的输出: 您需要此应用程序的新版本。\n请更新应用程序 感谢您提供的

为什么这个代码不起作用

public static void main(String[] args) {
    String s = "You need the new version for this. Please update app ...";
    System.out.println(s.replaceAll(". ", ".\\\\n").replaceAll(" ...", "..."));
}
这是我想要的输出:

您需要此应用程序的新版本。\n请更新应用程序


感谢您提供的信息。replaceAll方法将Regex作为第一个参数

所以你需要转义你的点(
),因为它在正则表达式中有特殊的含义,它匹配任何字符

System.out.println(s.replaceAll("\\. ", ".\\\\n").replaceAll(" \\.\\.\\.", "..."));

但是,对于给定的输入,您可以简单地使用
String.replace
方法,因为它不使用
Regex
,并且有一个额外的优点。

是一个特殊的Regex字符,可以匹配任何字符。你需要像这样逃逸:
\\.

因此,要匹配三个点,必须使用以下正则表达式:
“\\.\.\.\.\.\。”

你想要的是

s.replaceAll("\\. ", ".\n").replaceAll(" \\.\\.\\.", "...")

您不应该使用
replaceAll
-请改用
replaceAll
在此处不需要正则表达式时使用正则表达式(因此它将不必要地低效)

(还请注意,我已在此处将
“\\\\n”
替换为
“\\\n”
,这将生成所需的输出。)

尝试

    System.out.println(s.replace(". ", ".\n").replace(" ...", "..."));
这给

You need the new version for this.
Please update app...

你的实际输出是什么?你想把输出分成两行吗?\n是否打算成为新行字符?@EvgeniyDorofeev如果他这样做,我认为他会在两行上发布输出。您的版本会生成“您需要新版本。\\n请更新应用程序…”仍然错误:您需要新版本。\n请更新应用程序\n不是它的'\'+'n'@EvgeniyDorofeev OP不需要新行字符-他实际上想要文本中的“\n”(在这里生成)
s.replace(“.”,“\\n”).replace(“…”,“…”).equals(“您需要新的版本进行此操作。\\n请更新应用程序…”)==true
。使用
replaceAll
在这里有点过分-您可能希望在回答中提到这一点。
You need the new version for this.
Please update app...