Currency Regular Expression

前端 未结 3 1525
执念已碎
执念已碎 2020-12-06 08:13

I think I created a working regular expression for what I need. Just wondering if anyone can break it or see a shorter way to write it.

The regular expression shoul

3条回答
  •  温柔的废话
    2020-12-06 09:07

    Here is one shorter alternative (56 chars to your 114), which will work in almost all regex flavors:

    ^\$?(?=\(.*\)|[^()]*$)\(?\d{1,3}(,?\d{3})?(\.\d\d?)?\)?$
    

    Example: http://www.rubular.com/r/qtYHEVzVK7

    Explanation:

    ^                # 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
    

提交回复
热议问题