2012-08-08 94 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