Java 库检查字符串是否包含数字*没有*异常
我正在寻找一种方法,如果传递的字符串是有效数字(例如“123.55e-9”、“-333,556”),则返回布尔值。 我不想只想这样做:
public boolean isANumber(String s) {
try {
BigDecimal a = new BigDecimal(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
显然,该函数应该使用状态机(DFA)来解析字符串,以确保无效的示例不会欺骗它(例如“-21,22.22. 2”、“33-2”)。 你知道是否存在这样的图书馆吗? 我真的不想自己写它,因为这是一个如此明显的问题,我确信我会重新发明轮子。
谢谢,
尼克
I'm looking for a method that returns a boolean if the String it is passed is a valid number (e.g. "123.55e-9", "-333,556"). I don't want to just do:
public boolean isANumber(String s) {
try {
BigDecimal a = new BigDecimal(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Clearly, the function should use a state machine (DFA) to parse the string to make sure invalid examples don't fool it (e.g. "-21,22.22.2", "33-2"). Do you know if any such library exists? I don't really want to write it myself as it's such an obvious problem that I'm sure I'd be re-inventing the wheel.
Thanks,
Nick
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会避免重新发明这种方法并使用 Apache Commons。 如果您使用 Spring、Struts 或许多其他常用的 java 库,它们通常包含 Apache commons。 您将需要 commons-lang.jar 文件。 这是 NumberUtils 你会想要:
I would avoid re-inventing this method and go with Apache Commons. If your using Spring, Struts or many other commonly used java libraries, they often have Apache commons included. You will want the commons-lang.jar file. Here is the method in NumberUtils you would want:
使用 正则表达式
use a regexp
确切的正则表达式在 Javadocs 中为
Double.valueOf(String)
。The exact regular expression is specified in the Javadocs for
Double.valueOf(String)
.这是一个基于正则表达式的实用函数,运行良好(无法在正则表达式中安装“”检查,同时保持其可读性):
Here is a regexp based utility function working fine (couldn't fit the "" check in the regexp while keeping it readable):
是的,正则表达式应该可以解决问题。 我只知道 .Net 正则表达式,但所有正则表达式语言都非常相似,所以这应该可以帮助您入门。 我没有对其进行测试,因此您可能需要使用 Java 正则表达式类稍微尝试一下。
一些正则表达式控制语法:
? - 可选元素
| - 或运算符。 基本上,如果格式正确,我允许带或不带逗号的数字。
[ ] - 允许的字符集
{ , } - 元素的最小最大值
* - 任意数量的元素,0 到无穷大
+ - 至少一个元素,1 到无穷大
\ - 转义字符
。 - 任何字符(因此它被转义)
Yeah a regular expression should do the trick. I only know .Net regexp but all regex languages are fairly similar so this should get you started. I didn't test it so you might want to kick it around a bit with the Java regex class.
Some of the Regex control syntax:
? - Optional element
| - OR operator. Basically I allowed numbers with or without commas if they were formatted correctly.
[ ] - Set of allowed characters
{ , } - Minimum maximum of element
* - Any number of elements, 0 to infinity
+ - At least one element, 1 to infinity
\ - Escape character
. - Any character (Hence why it was escaped)