Best way to get integer part of the string “600sp”

2020-03-01 09:49发布

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!

6条回答
一夜七次
2楼-- · 2020-03-01 10:06

You can use

Integer.valueOf("0" + "600sp".replaceAll("(\\d*).*", "$1"))

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!

查看更多
神经病院院长
3楼-- · 2020-03-01 10:06

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.

查看更多
趁早两清
4楼-- · 2020-03-01 10:21

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

mystr.split("[a-z]")[0]
查看更多
家丑人穷心不美
5楼-- · 2020-03-01 10:27

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.

查看更多
爷、活的狠高调
6楼-- · 2020-03-01 10:31

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.

查看更多
我只想做你的唯一
7楼-- · 2020-03-01 10:31

For a shorter and less specific solution, add more context.

StringBuffer numbers = new StringBuffer();
for(char c : "asdf600sp".toCharArray())
{
  if(Character.isDigit(c)) numbers.append(c);
}

System.out.println(numbers.toString());

In the light of the new info, an improved solution:

Integer.valueOf("600sp".replace("sp",""));
查看更多
登录 后发表回答