正则表达式匹配货币或百分比

时间:2011-12-06 16:53:21

标签: javascript regex currency

我需要匹配以下值,而我当前的Regular Expression似乎无法匹配%值或没有-$

我需要匹配的值:

  

$ 123.45 - 匹配

     

- $ 123.45 - 匹配

     

123.45 - 需要匹配

     

-123.45 - 匹配

     

.99 - 需要匹配

     

- 。99 - 匹配

     

7% - 需要匹配

     

-7% - 需要匹配

     

500 - 需要匹配

正则表达式:

^[-$][$]?\d*(?:\.\d{0,2})?$

4 个答案:

答案 0 :(得分:6)

你走了:

/^-?\$?[0-9]*\.?([0-9]{2})?%?$/

答案 1 :(得分:0)

$str = " 
$123.45 - Match
-$123.45 - Match
123.45 - Needs Matched
-123.45 - Match
.99 - Needs Matched
-.99 - Match
7% - Needs Matched
-7% - Needs Matched
500 - Needs Matched
";

preg_match_all('#-?[$]?[0-9]*\.?[0-9]{2}+[%]?#i',$str, $res);
print_r($res);

这会将网络广泛传播到广泛但发现 - $ 123.12%为数字

答案 2 :(得分:0)

/^-?\$?[0-9]*(\.?[0-9]{1,2})?%?$/

答案 3 :(得分:0)

我改编了akellehe的答案,以匹配一系列货币符号:

var regex = new RegExp("^-?[^0-9]?[0-9]*[0-9\u002e]+%?$");

并捕获输出以进行更多分析:

var regex = new RegExp("^(-?)([^0-9]?)([0-9]*[0-9\u002e]+)(%?)$");
// $1 captures the negative sign,
// $2 captures the currency symbol
// $3 captures the number
// $4 captures the percent sign