我正在使用这个正则表达式:
^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$
此正则表达式匹配带逗号或不带逗号的美元货币金额
我想用货币格式匹配 1000 到 2000 之间的数字。
例子:
匹配$1,500.00 $2000.0 $1100.20 $1000
不匹配$1,000.0000 $3,000 $2000.1 $4,000 $2500.50
怎么样:
/^\$(?:1,?\d{3}(?:\.\d\d?)?|2000(?:\.00?)?)$/
解释:
^ the beginning of the string
----------------------------------------------------------------------
\$ '$'
----------------------------------------------------------------------
(?: group, but do not capture:
----------------------------------------------------------------------
1 '1'
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
\d{3} digits (0-9) (3 times)
----------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\. '.'
----------------------------------------------------------------------
\d digits (0-9)
----------------------------------------------------------------------
\d? digits (0-9) (optional (matching the
most amount possible))
----------------------------------------------------------------------
)? end of grouping
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
2000 '2000'
----------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\. '.'
----------------------------------------------------------------------
0 '0'
----------------------------------------------------------------------
0? '0' (optional (matching the most
amount possible))
----------------------------------------------------------------------
)? end of grouping
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
[$]\([1][[:digit:]]\{3\}\|2000\)\(,[[:digit:]]+\|\)
这个表达式定义了这种语言:
美元后跟 1 xyz 或 2000。
最后,可选地后跟逗号和 1 个或多个数字