2012-08-08 62 views
0

我使用正则表达式:货币正则表达式匹配数字范围

^\$?([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

+4

检查,一些谎言通过使用正则表达式在一个范围内是不使用r的一个很好的例子ight工作的工具。将字符串转换为数字值并使用'x> = 1000 && x <= 2000'。 – 2012-08-08 13:47:16

+2

完全同意。如果需要,首先用正则表达式验证以确保您有一个有效的货币数字,然后从中提取数字,转换为整数/浮点数和范围检查。 – Adrian 2012-08-08 13:50:05

回答

1
[$]\([1][[:digit:]]\{3\}\|2000\)\(,[[:digit:]]+\|\) 

这个表达式定义该语言:

  • 美元随后用1 XYZ或200 0

  • 终于,后面可以跟逗号和1个或多个数字

1

如何:

/^\$(?: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