正则表达式表示带逗号的浮点数

Regex for float with comma

本文关键字:浮点数 表示 正则表达式      更新时间:2023-09-26

我需要验证一个输入,包含一个项目的价格。值可能是..

1.2
1.02 
30,000 
30,000.00 
30000000

所以我需要正则表达式来支持这一点。

这应该有效

/^[0-9]{1,3}(?:',[0-9]{3})*(?:'.[0-9]{1,2})?$/

想出了这个:

^'d+([',]'d+)*(['.]'d+)?$

用于检测它是否是价格的正则表达式。将其分解为多个部分:

^     # start of string
'd+   # this matches at least 1 digit (and is greedy; it matches as many as possible)
(     # start of capturing group
 [',] # matcher group with an escaped comma inside
 'd+  # same thing as above; matches at least 1 digit and as many as possible
)*    # end of capturing group, which is repeated 0 or more times
      # this allows prices with and without commas.
(     # start of capturing group
 ['.] # matcher group with an escaped fullstop inside
 'd+  # same thing; refer to above
)?    # end of capturing group, which is optional.
      # this allows a decimal to be optional
$     # end of string

我建议您在创建正则表达式时尝试 http://regex101.com。

这应该有效

^(?:[1-9]'d*|0)?(?:'.'d+)?$