获取字符串“600sp”整数部分的最佳方法?
我有一个字符串,比如“600sp”,我希望从中获取整数部分(600)。
如果我这样做 Integer.valueOf("600sp")
由于在字符串中遇到非数字值“s”,我会收到异常。
获取整数部分最快最干净的方法是什么?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您的字符串格式始终是数字后跟一些字符,那么试试这个
If your string format is always going to be number followed by some characters, then try this
根据输入的限制,您可能最好使用正则表达式。
这个正则表达式翻译为“给我字符串开头至少有 1 位数字的一组连续数字”。如果您有其他约束,例如解析实数而不是整数,那么您需要修改代码。
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:
您可以使用
注意:
使用此正则表达式,您将仅保留初始数字。
编辑:
"0" +
用于在我没有数字时不会崩溃。谢谢@jherico!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!如果字符串保证(如您所说)是一个整数,后跟“sp”,我建议不要使用更通用的正则表达式解析器,它也接受其他变体(应作为错误被拒绝)。
只需测试它是否以“sp”结尾,然后解析没有最后两个字符的子字符串。
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.
我知道这个问题已经得到了回答,但是您是否考虑过
java.util.Scanner
?它似乎完全符合要求,无需正则表达式或其他更复杂的字符串实用程序。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.