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!
You can use
Note:
With this regex you will keep only the initial numbers.
Edit: The
"0" +
is used to not crash when i have no digits. Tks @jherico!I know that this has already been answered, but have you considered
java.util.Scanner
? It seems to fit the bill perfectly without regex's or other more complex string utilities.If your string format is always going to be number followed by some characters, then try this
If the string is guaranteed (as you say it is) to be an integer followed by "sp", I would advise against using a more generic regular expression parser, which would also accept other variations (that should be rejected as errors).
Just test if it ends in "sp", an then parse the substring without the last two characters.
Depending on the constraints of your input, you may be best off with regex.
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.
For a shorter and less specific solution, add more context.
In the light of the new info, an improved solution: