Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove end of line characters from end of Java String

Tags:

java

string

regex

I have a string which I'd like to remove the end of line characters from the very end of the string only using Java

"foo\r\nbar\r\nhello\r\nworld\r\n"

which I'd like to become

"foo\r\nbar\r\nhello\r\nworld"

(This question is similar to, but not the same as question 593671)

like image 710
Iain Sproat Avatar asked Jun 23 '10 09:06

Iain Sproat


People also ask

How do you remove the end of a line in Java?

The chomp() method of the StringUtils class in Commons LangS can be used to remove the last newline character from a String. A newline is defined as \n, \r, and \r\n. If a String ends in \n\r, only the \r will be removed since this the \r is considered to be one newline.

How do I remove a newline from the end of a string?

Use the trim() method to remove the line breaks from the start and end of a string, e.g. str. trim() . The trim method removes any leading or trailing whitespace from a string, including spaces, tabs and all line breaks.


2 Answers

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
like image 113
polygenelubricants Avatar answered Oct 07 '22 11:10

polygenelubricants


Wouldn't String.trim do the trick here?

i.e you'd call the method .trim() on your string and it should return a copy of that string minus any leading or trailing whitespace.

like image 25
Richard Walton Avatar answered Oct 07 '22 11:10

Richard Walton