Search code examples
javaregexwhitespacetrim

How to replace last character in a string with white space in the end


I have this kind of scenario in java, the last character : or - in a string should be replaced with "".

Example:

String value = "data - ";

String value2 = "data :";

value.replaceAll("[-:]$","");

value2.replaceAll("[:-]$","");

System.out.println(value);

System.out.println(value2);

Output:

data -

data

I think the whitespace treated as the last character and does not match the regex provide, can someone help me with this scenarion? thank you.


Solution

  • private static String strip(String s) {
        if (s.endsWith(":") || s.endsWith("-")){
            s = s.substring(0, s.length()-1);
        }
        return s;
    }