[英]Strange regular expression behaviour for decimal numbers in java
The following is my java code 以下是我的java代码
Pattern p = Pattern.compile("-?\\d*\\.?\\d*");
Matcher m = p.matcher("the numbers are -3.4 and 132");
while (m.find()) {
System.out.println(m.group());
}
But it fails to match either number. 但是它不能匹配任何一个数字。 Can anyone shed some light upon this program? 谁能给这个程序一些启发?
Your regex matches the numbers, but also every inter-char. 您的正则表达式不仅要匹配数字,还要匹配每个字符间的字符。 Use \\\\d+
instead of your second \\\\d*
for example. 例如,使用\\\\d+
代替第二个\\\\d*
。
I usually use the following regex to match numbers (already escaped for Java): 我通常使用以下正则表达式来匹配数字(对于Java已经转义了):
[-+]?\\\\d*[.]?\\\\d+(?:[eE][-+]?\\\\d+)?
使用此正则表达式:
-?\\d+(?:\\.\\d+)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.