9

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)

Community
  • 1
  • 1
Iain Sproat
  • 5,210
  • 11
  • 48
  • 68

7 Answers7

17

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


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

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • and the second option will leave any leading whitespace? – Iain Sproat Jun 23 '10 at 10:02
  • 2
    `trim()` will also remove leading whitespace, that's not what is being asked. – Jesper Jun 23 '10 at 10:04
  • @sprocket: which second option are you talking about? The solution in this reply will leave leading whitespace intact. – Joachim Sauer Jun 23 '10 at 10:08
  • @polygenelubricants does this deal with (as Jesper asked in a comment on another answer) the cases where a string ends with "\n\r" instead of "\r\n", or only "\n" without "\r"? – Iain Sproat Jun 23 '10 at 10:17
  • @sprocketonline: yes, character class is a set, i.e. unordered. `[ab]` is the same as `[ba]`, a character class matching `a` or `b`. Order only matters when you're defining a range, i.e. `[0-9]`, not `[9-0]`. `[ab]` is not the same as `ab`. – polygenelubricants Jun 23 '10 at 10:19
3

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.

Richard Walton
  • 4,789
  • 3
  • 38
  • 49
  • He explicitly said: "... from the very end of the string only", so he doesn't want to remove leading whitespace. – Jesper Jun 23 '10 at 10:03
  • Yeah I know. Still, the example string didn't have any leading whitespace so I thought it was worth a shot... – Richard Walton Jun 23 '10 at 10:08
2

The Apache Commons Lang StringUtils.stripEnd(String str, String stripChars) will do the trick; e.g.

    String trimmed = StringUtils.stripEnd(someString, "\n\r");

If you want to remove all whitespace at the end of the String:

    String trimmed = StringUtils.stripEnd(someString, null);
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

Well, everyone gave some way to do it with regex, so I'll give a fastest way possible instead:

public String replace(String val) {
    for (int i=val.length()-1;i>=0;i--) {
        char c = val.charAt(i);
        if (c != '\n' && c != '\r') {
            return val.substring(0, i+1);
        }
    }
    return "";
}

Benchmark says it operates ~45 times faster than regexp solutions.

bezmax
  • 25,562
  • 10
  • 53
  • 84
  • I think you can do faster without `toCharArray()` using `charAt` instead. – polygenelubricants Jun 23 '10 at 10:37
  • @polygenelubricants: Indeed. Checked java source and you are right. Somehow I thought that toCharArray just returns the inner value of string. But after looking at the sources of java I see it copies the array to a new one. Gonna change my answer too. – bezmax Jun 23 '10 at 10:42
2

If you have Google's guava-librariesin your project (if not, you arguably should!) you'd do this with a CharMatcher:

String result = CharMatcher.any("\r\n").trimTrailingFrom(input);
Cowan
  • 37,227
  • 11
  • 66
  • 65
1
String text = "foo\r\nbar\r\nhello\r\nworld\r\n";
String result = text.replaceAll("[\r\n]+$", "");
Jesper
  • 202,709
  • 46
  • 318
  • 350
0
"foo\r\nbar\r\nhello\r\nworld\r\n".replaceAll("\\s+$", "")
or
"foo\r\nbar\r\nhello\r\nworld\r\n".replaceAll("[\r\n]+$", "")
Favonius
  • 13,959
  • 3
  • 55
  • 95