Remove End of Line Characters from Java String

How to remove newlines from beginning and end of a string?

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();

Remove end of line characters from end of Java String

You can use s = s.replaceAll("[\r\n]+$", "");. This trims the \r and \n characters at the end of the string

The regex is explained as follows:

  • [\r\n] is a character class containing \r and \n
  • + is one-or-more repetition of
  • $ is the end-of-string anchor

References

  • regular-expressions.info/Anchors, Character Class, Repetition

Related topics

You can also use String.trim() to trim any whitespace characters from the beginning and end of the string:

s = s.trim();

If you need to check if a String contains nothing but whitespace characters, you can check if it isEmpty() after trim():

if (s.trim().isEmpty()) {
//...
}

Alternatively you can also see if it matches("\\s*"), i.e. zero-or-more of whitespace characters. Note that in Java, the regex matches tries to match the whole string. In flavors that can match a substring, you need to anchor the pattern, so it's ^\s*$.

Related questions

  • regex, check if a line is blank or not
  • how to replace 2 or more spaces with single space in string and delete leading spaces only


Related Topics



Leave a reply



Submit