英文:
Removing a hard Enter from a String
问题
最佳方法来从字符串中移除硬回车是使用以下代码:
in = in.replaceAll("\\r\\n","");
System.out.println(in);
预期的输出是:strengthened columns with GRPES
英文:
What is the best way to remove a hard enter from a String?
Input:
String in= "strengthened columns
with GRPES
";
Expected output: strengthened columns with GRPES
I tried the below code, but it's not working for me.
in = in.replaceAll("\\r\\n","");
System.out.println(in);
答案1
得分: 1
除非你今天没有特定的理由要使用java-7,否则这是一个使用java 13或更高版本的解决方案。
String in = """
strengthened columns
with GRPES
""";
in = in.replaceAll("\\n", "");
System.out.println(in);
我注意到问题标记了java-7,如果你正在寻找特定版本的解决方案,请告诉我。
英文:
Unless you don't have a specific reason to use java-7 today, Here's a solution using java 13 or above
String in= """
strengthened columns
with GRPES
""";
in = in.replaceAll("\\n","");
System.out.println(in);
I have observed the question is tagged with java-7, do let me know if you are looking for a solution specific to the version
答案2
得分: 0
实际上,当你使用正则表达式时,你不需要转义标准的转义序列。此外,你不需要指定转义序列的顺序 - 你只需要消除任何类型的行分隔符,所以可以使用以下代码:
in = in.replaceAll("[\\r\\n]", "");
在较新版本的Java中,也可以这样写:
in = in.replaceAll("\\R", "");
英文:
Actually you don't escape standard escape sequences when you use regexes. Also you don't want to specify an order of escape sequences - you just want to eliminate any type of line separator, so
in = in.replaceAll("[\r\n]","");
With later versions of Java, that could probably be
in = in.replaceAll("\\R","");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论