是否有正则表达式匹配最多7位数的浮点数?

时间:2013-02-19 17:42:37

标签: regex

我正在寻找一个匹配最多7位数的浮点数的正则表达式。我无法弄清楚如何处理小数点。甚至可以将它与正则表达式相匹配吗?小数点左边必须至少有1位数字,右边有0-6位数字,但总位数必须是7或更少。

示例:

好:

  • 1.234567
  • 0.1
  • 1234567
  • 1

坏:

  • 0.1234567
  • 12345678
  • 1.2.34567

1 个答案:

答案 0 :(得分:7)

以下内容应该有效:

^(?!.*\..*\.|\d{8})\d[\d.]{,7}$

示例:http://www.rubular.com/r/gglVngm0pH

说明:

^            # beginning of string anchor
(?!          # start negative lookahead (fail if following regex can match)
   .*\..*\.    # two or more '.' characters exist in the string
   |           # OR
   \d{8}       # eight consecutive digits in the string
)            # end negative lookahead
\d           # match a digit
[\d.]{,7}    # match between 0 and 7 characters that are either '.' or a digit
$            # end of string anchor