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)
You can use
s = s.replaceAll("[\r\n]+$", "");. This trims the\rand\ncharacters at the end of the stringThe regex is explained as follows:
[\r\n]is a character class containing\rand\n+is one-or-more repetition of$is the end-of-string anchorReferences
Related topics
You can also use
String.trim()to trim any whitespace characters from the beginning and end of the string:If you need to check if a
Stringcontains nothing but whitespace characters, you can check if itisEmpty()aftertrim():Alternatively you can also see if it
matches("\\s*"), i.e. zero-or-more of whitespace characters. Note that in Java, the regexmatchestries to match the whole string. In flavors that can match a substring, you need to anchor the pattern, so it’s^\s*$.Related questions