Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get integer part of the string "600sp"?

I have a string, say "600sp" from which I wish to obtain the integer part (600).

If I do Integer.valueOf("600sp") I get an exception due to the non-numeric value "s" which is encountered in the string.

What is the fastest cleanest way to grab the integer part?

Thanks!

like image 686
Brad Hein Avatar asked Aug 24 '10 00:08

Brad Hein


2 Answers

If your string format is always going to be number followed by some characters, then try this

mystr.split("[a-z]")[0]
like image 191
Chuk Lee Avatar answered Sep 20 '22 16:09

Chuk Lee


Depending on the constraints of your input, you may be best off with regex.

    Pattern p = Pattern.compile("(\\d+)");
    Matcher m = p.matcher("600sp");
    Integer j = null;
    if (m.find()) {
        j = Integer.valueOf(m.group(1));
    }

This regular expression translates as 'give me the set of contiguous digits at the beginning of the string where there is at least 1 digit'. If you have other constraints like parsing real numbers as opposed to integers, then you need to modify the code.

like image 25
Jherico Avatar answered Sep 20 '22 16:09

Jherico