从字符串中删除硬回车

huangapple go评论56阅读模式
英文:

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","");

huangapple
  • 本文由 发表于 2023年2月6日 19:58:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定