How to remove a ^M character java
-
29-09-2019 - |
Question
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.
OTHER TIPS
I'd write it like this:
if (masterValue.endsWith("\r")) {
masterValue = masterValue.substring(0, masterValue.length() - 1);
}
I see no point in creating a named constant for the String "\r".
By the way, your second attempt is incorrect because:
String.contains("\r")
tells you if the String contains a carriage return, not if it ends with a carriage return,- the second argument of
String.substring(int, int)
is the index of the end character; i.e. the position first character that should NOT be in the substring, and - the length of
"\r"
is one.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow