4

我对 reg 表达式相当陌生,我正在努力想出一个价格字段的正则表达式。

我想用

var price = $('#new_price').val().replace(/*regex*/, '');

去除任何不需要的字符。

价格可以是 int 即 10 或小数到 2dp 即 9.99

基本上我想要删除任何与标准货币格式不匹配的东西。

或者

我想要一个正则表达式来检查(使用.match(regex))该字段是否采用所需的格式。

如果有人可以快速为我编写这些正则表达式中的任何一个并向我解释,那么我知道未来我会非常感激。

4

1 回答 1

12

您可以使用此正则表达式去除任何非数字或.字符:/[^\d\.]/g

所以:

$('#new_price').val().replace(/[^\d\.]/g, '');

这个正则表达式的工作方式如下:

/  -> start of regex literal
[  -> start of a "character class". Basically you're saying I to match ANY of the
      characters in this class.
^  -> this negates the character class which says I want anything that is NOT in 
      this character class
\d -> this means digits, so basically 0-9.
\. -> Since . is a metacharacter which means "any character", we need to escape 
      it to tell the regex to look for the actual . character
]  -> end of the character class
/  -> end of the regex literal.
g  -> global flag that tells the regex to match every instance of the pattern.

所以基本上这会寻找任何不是数字或小数点的东西。

要查看它的格式是否正确,您可以检查值是否匹配:

/\d*(\.\d{0, 2})?/

你可以像这样使用它:

if(/^\d*(\.\d{0, 2})?$/.test($('#new_price').val()) {
   ...
   ...
}

因此,if块中的代码只有在匹配模式时才会运行。这是正则表达式的解释:

/        -> start of regex literal
^        -> anchor that means "start of string". Yes the ^ is used as an anchor
            and as a negation operator in character classes :) 
\d       -> character class that just matches digits
*        -> this is a regex metacharacter that means "zero or more" of the 
            preceding. So this will match zero or more digits. You can change
            this to a + if you always want a digit. So instead of .99, you want
            0.99.
(        -> the start of a group. You can use this to isolate certain sections or
            to backreference.
\.       -> decimal point
\d{0, 2} -> zero to two numbers.
)        -> end of the group
?        -> regex metacharacter that means "zero or one" of the preceding. So 
            what this means is that this will match cases where you do have 
            numbers after the decimal and cases where you don't.
$        -> anchor that means "end of string"
/        -> end of the regex literal
于 2012-08-30T15:22:21.990 回答