以下是我的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());
}
但它无法匹配任何一个数字。有人能解释一下这个程序吗?
最佳答案
您的正则表达式匹配数字,但也匹配每个字符间。例如,使用 \\d+
而不是第二个 \\d*
。
我通常使用以下正则表达式来匹配数字(已经为 Java 转义):
[-+]?\\d*[.]?\\d+(?:[eE][-+]?\\d+)?
关于java - java中十进制数的奇怪正则表达式行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017942/