How to remove ^ M character character

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';

It seems uncomfortable to me.

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

Then I went to the following:

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

// - 3, since we start with 0 (1), end with the end with \ n (2), and we need to remove 1 char (3)

But this also seems uncomfortable.

Can you offer a lighter, more elegant solution?

+3
source share
2 answers

Regexes can support snapping to the end of a line, you know. (See this Javadoc page for more information)

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

This also takes care of fixing \ r \ n → \ n, I suppose.

+9

:

if (masterValue.endsWith("\r")) {
    masterValue = masterValue.substring(0, masterValue.length() - 1);
}

"\ r".

, , :

  • String.contains("\r") , , ,
  • String.substring(int, int) - ; , ,
  • "\r" .
+3

Source: https://habr.com/ru/post/1751588/


All Articles