4

私は正規表現にかなり慣れていないので、価格フィールドの正規表現を考え出すのに苦労しています。

使いたい

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

不要な文字を削除します。

価格は 10 の int または 2 dp の 9.99 の 10 進数です。

基本的に、標準の通貨形式に一致しないものはすべて削除したいと考えています。

また

.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 に答える