javaandroidstringsubstringapache-stringutils

Would a forward slash cause issues with StringUtils.remove and .removeEnd?


I'm extracting a piece of text from a webpage using JSoup and cleaning up the resulting string with Apache's StringUtils library. The first pass, using substringBetween to grab just the text in parentheses works like a charm, returning a string (value) of digits followed by units (e.g., 2500mg/kg).

But when I try to drop the trailing units (mg/kg) using removeEnd:

value = StringUtils.removeEnd(value, "mg/kg");

... I always get back the original string completely unchanged -- 2500mg/kg.

I tried using just plain remove and removeEndIgnoreCase (just in case), but I couldn't get anything to work.

First I tried this as an alternative:

value = value.substring(0, value.indexOf("m"));

... and that worked for a couple of tests and then failed(??). So then I tried:

value = StringUtils.substring(value, 0, -5);

This seems to be working fine, but I'm not wild about it since it isn't specific about what it's removing. I would really prefer to use removeEnd (or something similar) here (plus I'm new at this, so I always want to know why something doesn't work).

Can anyone shed some light on what I'm doing wrong? I couldn't find any restrictions on special characters in the StringUtils docs, but could the forward slash be causing an issue? Or should I be worrying about invisible control characters?


Solution

  • Works for me (with commons-lang3-3.7.jar):

    public static void main(String[] args) {
    
        String value = "2500mg/kg";
        System.out.println (StringUtils.removeEnd(value, "mg/kg"));
    }
    
    
    2500
    
    Process finished with exit code 0
    

    Are you sure your original string ends with mg/kg? Dump the contents of the string to sysout before your attempted removeEnd, or check the value using the debugger.

    If you suspect there's a control character at the end, you could use another commons-lang utility to display the string:

    StringEscapeUtils.escapeJava(value)