Search code examples
dostruncatecarriage-return

How to remove a ^M character java


Problem: If String ends with \r, remove \r

I started with something like this

if (masterValue.endsWith(CARRIAGE_RETURN_STR)) {
  masterValue = masterValue.replace(CARRIAGE_RETURN_STR, "");
}

where

public static final String CARRIAGE_RETURN_STR = (Character.toString(Constants.CARRIAGE_RETURN));
public static final char CARRIAGE_RETURN = '\r';

This seems awkward to me.

Is there an easy way to just remove \r character?

I then moved on to this:

if (value.contains(CARRIAGE_RETURN_STR)) {
   value = value.substring(0, value.length()-3);

//-3 because we start with 0 (1), line ends with \n (2) and we need to remove 1 char (3)

But this too seems awkward .

Can you suggest a easier, more elegant solution?


Solution

  • Regexes can support end-of-string anchoring, you know. (See this Javadoc page for more information)

    myString.replaceAll("\\r$", "");
    

    This also takes care of fixing \r\n --> \n, I believe.