-3

I have strings that I need to remove the trailing characters from. There are several types, here are some examples:

"82.882ft" "101in" "15.993ft³" "10.221mm"

Etc. I need to remove the length delimiters so I will be left with strings:

"82.882" "101" "15.993" "10.221"

Ideas?

GregMa
  • 740
  • 2
  • 10
  • 25
  • 16
    I have an idea: write code. – Maroun Oct 19 '15 at 15:37
  • I don't see a clean way to do this with substring functions. – ergonaut Oct 19 '15 at 15:40
  • 1. Find the index of the first character that isn't part of the number (only you can know precisely what characters are permissible within the numbers) 2. take the substring up to that point – DJClayworth Oct 19 '15 at 15:44
  • Since the title of the other answer only said "non numeric characters", it didn't specify that it included a period (which is non numeric), thus I didn't think it was the same. Looking closer, they did include the period. – GregMa Oct 19 '15 at 16:31

3 Answers3

3

Just use regex:

String result = input.replaceAll("[^0-9.]", "");
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
3

Try using a replaceAll on the string, specifying all characters that are not a decimal point or number:

myString = myString.replaceAll("[^0-9\\.]","");

"^0-9\." means all characters that are not a number 0 through 9, or a decimal. The reason why we put two slashes are to escape the period, as it has a different connotation in a Java regex than the literal character '.'.

MrPublic
  • 520
  • 5
  • 16
0

Regular Expressions probably works best for this.

    Pattern lp = Pattern.compile("([\\d.]+)(.*)");

    // Optional cleanup using Apache Commons StringUtils
    currentInput = StringUtils.upperCase(
            StringUtils.deleteWhitespace(currentInput));

    Matcher lpm = lp.matcher(currentInput);
    if( lpm.matches() )
    {
        // Values
        String value = lpm.group(1);

        // And the trailing chars for further processing
        String measure = lpm.group(2);
    }
kervin
  • 11,672
  • 5
  • 42
  • 59