如何从字符串的开头和结尾删除换行符?

发布于 2024-12-05 05:34:45 字数 57 浏览 0 评论 0 原文

我有一个字符串,其中包含一些文本,后跟一个空行。保留文本部分但删除末尾的空白换行符的最佳方法是什么?

I have a string that contains some text followed by a blank line. What's the best way to keep the part with text, but remove the whitespace newline from the end?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

浅语花开 2024-12-12 05:34:45

使用 String.trim() 方法从字符串的开头和结尾删除空格(空格、换行符等)。

String trimmedString = myString.trim();

Use String.trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.

String trimmedString = myString.trim();
硪扪都還晓 2024-12-12 05:34:45
String.replaceAll("[\n\r]", "");
String.replaceAll("[\n\r]", "");
写给空气的情书 2024-12-12 05:34:45

这段Java代码完全按照问题标题中的要求进行操作,即“从字符串java的开头和结尾删除换行符”:

String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")

仅从行尾删除换行符:

String.replaceAll("[\n\r]$", "")

仅从行首删除换行符:

String.replaceAll("^[\n\r]", "")

This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":

String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")

Remove newlines only from the end of the line:

String.replaceAll("[\n\r]$", "")

Remove newlines only from the beginning of the line:

String.replaceAll("^[\n\r]", "")
迷乱花海 2024-12-12 05:34:45

tl;dr

String cleanString = dirtyString.strip() ; // Call new `String::string` method.

String::strip...

旧的 String::trim 方法有一个 空白的奇怪定义。

正如此处所述,Java 11 添加了新的 strip... 方法到 String 类。它们使用更符合 Unicode 的空白定义。请参阅类 JavaDoc 中此定义的规则 字符::isWhitespace

示例代码。

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");

或者您可以删除 只是前导只是尾随 空格。

您没有确切提及代码点组成换行符。我想您的换行符可能包含在 strip 所针对的代码点列表中:

  • 它是 Unicode 空格字符(SPACE_SEPARATOR、LINE_SEPARATOR 或 PARAGRAPH_SEPARATOR),但也不是不间断空格('\ u00A0'、'\u2007'、'\u202F')。
  • 它是“\t”,U+0009 水平制表。
  • 它是“\n”,U+000A 换行符。
  • 它是“\u000B”,U+000B 垂直制表。
  • 它是“\f”,U+000C 换页。
  • 它是'\r',U+000D 回车符。
  • 它是“\u001C”,U+001C 文件分隔符。
  • 它是“\u001D”,U+001D 组分隔符。
  • 它是 '\u001E',U+001E 记录分隔符。
  • 是'\u001F',U+0

tl;dr

String cleanString = dirtyString.strip() ; // Call new `String::string` method.

String::strip…

The old String::trim method has a strange definition of whitespace.

As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.

Example code.

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");

Or you can strip just the leading or just the trailing whitespace.

You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\t', U+0009 HORIZONTAL TABULATION.
  • It is '\n', U+000A LINE FEED.
  • It is '\u000B', U+000B VERTICAL TABULATION.
  • It is '\f', U+000C FORM FEED.
  • It is '\r', U+000D CARRIAGE RETURN.
  • It is '\u001C', U+001C FILE SEPARATOR.
  • It is '\u001D', U+001D GROUP SEPARATOR.
  • It is '\u001E', U+001E RECORD SEPARATOR.
  • It is '\u001F', U+0
开始看清了 2024-12-12 05:34:45

如果您的字符串可能为 null,请考虑使用 StringUtils.trim() - String.trim()

If your string is potentially null, consider using StringUtils.trim() - the null-safe version of String.trim().

北城半夏 2024-12-12 05:34:45

如果您只想删除字符串开头和结尾(而不是中间)的换行符(不是空格、制表符),那么您可以使用以下方法

:用于从开头 (^) 和结尾 (< code>$) 的字符串:

 s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")

完整示例:

public class RemoveLineBreaks {
    public static void main(String[] args) {
        var s = "\nHello world\nHello everyone\n";
        System.out.println("before: >"+s+"<");
        s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
        System.out.println("after: >"+s+"<");
    }
}

它输出:

before: >
Hello world
Hello everyone
<
after: >Hello world
Hello everyone<

If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:

Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:

 s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")

Complete Example:

public class RemoveLineBreaks {
    public static void main(String[] args) {
        var s = "\nHello world\nHello everyone\n";
        System.out.println("before: >"+s+"<");
        s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
        System.out.println("after: >"+s+"<");
    }
}

It outputs:

before: >
Hello world
Hello everyone
<
after: >Hello world
Hello everyone<
女皇必胜 2024-12-12 05:34:45

我也将对此添加一个答案,因为虽然我有同样的问题,但提供的答案还不够。经过一番思考,我意识到使用正则表达式可以非常轻松地完成此操作。

要从

// Trim left
String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);

System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");

字符串的开头和结尾删除换行符

// Trim right
String z = "\n\nfrom the end\n\n";

System.out.println("-" + z.split("\\n+$", 2)[0] + "-");

我确信这不是修剪字符串的最高效的方法。但它似乎确实是内联此类操作的最干净、最简单的方法。

请注意,可以使用相同的方法来修剪两端字符的任何变体和组合,因为它是一个简单的正则表达式。

I'm going to add an answer to this as well because, while I had the same question, the provided answer did not suffice. Given some thought, I realized that this can be done very easily with a regular expression.

To remove newlines from the beginning:

// Trim left
String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);

System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");

and end of a string:

// Trim right
String z = "\n\nfrom the end\n\n";

System.out.println("-" + z.split("\\n+$", 2)[0] + "-");

I'm certain that this is not the most performance efficient way of trimming a string. But it does appear to be the cleanest and simplest way to inline such an operation.

Note that the same method can be done to trim any variation and combination of characters from either end as it's a simple regex.

攒一口袋星星 2024-12-12 05:34:45
String trimStartEnd = "\n TestString1 linebreak1\nlinebreak2\nlinebreak3\n TestString2 \n";
System.out.println("Original String : [" + trimStartEnd + "]");
System.out.println("-----------------------------");
System.out.println("Result String : [" + trimStartEnd.replaceAll("^(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])|(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])$", "") + "]");
  1. 字符串开头 = ^ ,
  2. 字符串结尾 = $ ,
  3. 正则表达式组合 = | ,
  4. 换行 = \r\n|[\n\x0B\x0C\r\u0085\u2028\u2029]
String trimStartEnd = "\n TestString1 linebreak1\nlinebreak2\nlinebreak3\n TestString2 \n";
System.out.println("Original String : [" + trimStartEnd + "]");
System.out.println("-----------------------------");
System.out.println("Result String : [" + trimStartEnd.replaceAll("^(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])|(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])$", "") + "]");
  1. Start of a string = ^ ,
  2. End of a string = $ ,
  3. regex combination = | ,
  4. Linebreak = \r\n|[\n\x0B\x0C\r\u0085\u2028\u2029]
知你几分 2024-12-12 05:34:45

试试这个

function replaceNewLine(str) { 
  return str.replace(/[\n\r]/g, "");
}

Try this

function replaceNewLine(str) { 
  return str.replace(/[\n\r]/g, "");
}
那伤。 2024-12-12 05:34:45

另一个优雅的解决方案。

String myString = "\nLogbasex\n";
myString = org.apache.commons.lang3.StringUtils.strip(myString, "\n");

Another elegant solution.

String myString = "\nLogbasex\n";
myString = org.apache.commons.lang3.StringUtils.strip(myString, "\n");
街角卖回忆 2024-12-12 05:34:45

对于在处理不同换行符时寻找问题答案的其他人:

string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", "");          // Java 8

这应该准确删除最后一个换行符并保留字符串中的所有其他空白,并适用于 Unix (\n)、Windows (\r\n) 和旧 Mac ( \r) 换行符:https://stackoverflow.com/a/20056634https://stackoverflow.com/a/49791415"\\R" 是 Java 8 在 Pattern 类中引入的匹配器: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

这通过了这些测试:

// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));

// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));

// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));

For anyone else looking for answer to the question when dealing with different linebreaks:

string.replaceAll("(\n|\r|\r\n)
quot;, ""); // Java 7
string.replaceAll("\\R
quot;, "");          // Java 8

This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

This passes these tests:

// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R
quot;, ""));

// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R
quot;, ""));

// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R
quot;, ""));
墨落画卷 2024-12-12 05:34:45
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文