货币正则表达式

gfr*_*ius 3 regex

我想我为我需要的东西创建了一个有效的正则表达式.只是想知道是否有人可以打破它或看到更短的方式来编写它.

正则表达式应验证以下内容......

  • 美元符号可选
  • 负数用括号表示,而不是减号
  • 如果为负数,则美元符号应在括号外
  • 逗号是可选的
  • 最大数量为999999.99
  • 最小号码是(999999.99)
  • 不必提供小数,但如果是,则不超过两位数

所以这里有一些有效的例子......

9
$9
$0.99
($999,999.99)
(999999)
($999999)
(999,999)
99,999.9
Run Code Online (Sandbox Code Playgroud)

这就是我想出的:

^\$?(((\d{1,6}(\.\d{1,2})?)|(\d{1,3},\d{3}(\.\d{1,2})?)|\(((\d{1,6}(\.\d{1,2})?)|(\d{1,3},\d{3}(\.\d{1,2})?))\)))$
Run Code Online (Sandbox Code Playgroud)

修正,我的规格是错误的,如果使用美元符号,它必须在括号内.

And*_*ark 10

这是一个较短的选择(对你的114个56个字符),它几乎适用于所有正则表达式:

^\$?(?=\(.*\)|[^()]*$)\(?\d{1,3}(,?\d{3})?(\.\d\d?)?\)?$
Run Code Online (Sandbox Code Playgroud)

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

说明:

^                # start of string anchor
\$?              # optional '$'
(?=              # only match if inner regex can match (lookahead)
   \(.*\)          # both '(' and ')' are present
   |               # OR
   [^()]*$         # niether '(' or ')' are present
)                # end of lookaheand
\(?              # optional '('
\d{1,3}          # match 1 to 3 digits
(,?\d{3})?       # optionally match another 3 digits, preceeded by an optional ','
(\.\d\d?)?       # optionally match '.' followed by 1 or 2 digits
\)?              # optional ')'
$                # end of string anchor
Run Code Online (Sandbox Code Playgroud)