gpt4 book ai didi

jquery - 数字的正则表达式

转载 作者:行者123 更新时间:2023-11-30 23:52:04 24 4
gpt4 key购买 nike

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

我想使用

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

删除任何不需要的字符。

价格可以是整数,即 10或小数点到 2dp 即 9.99

基本上,我希望删除任何与标准货币格式不匹配的内容。

或者

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

如果有人可以快速为我编写这些正则表达式并向我解释,以便我了解 future ,我将非常感激。

最佳答案

您可以使用此正则表达式删除任何非数字或 . 字符:/[^\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 block 中的代码仅在与模式匹配时才会运行。这是正则表达式的解释:

/        -> 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

关于jquery - 数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12200243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com