用于金额的 Javascript 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7689817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript regex for amount
提问by Oseer
I'm trying to get a regex for an amount:
我正在尝试获取一定数量的正则表达式:
ANY DIGIT + PERIOD (at least zero, no more than one) + ANY DIGIT (at least zero no more than two [if possible, either zero OR two])
ANY DIGIT + PERIOD(至少零,不超过一)+ ANY DIGIT(至少零不超过二[如果可能,零或二])
What I have is:
我所拥有的是:
/^\d+\.\{0,1}+\d{0,2)+$/
...obviously not working. Examples of what I'm trying to do:
...显然不起作用。我正在尝试做的示例:
123 valid
123 有效
123.00 valid
123.00 有效
12.34.5 invalid
12.34.5 无效
123.000 invalid
123.000 无效
Trying to match an amount with or without the period. If the period is included, can only be once and no more than two digits after.
尝试匹配带有或不带有句号的金额。如果包含句点,则只能是一次,并且不能超过两位数。
回答by Matt Ball
Make the decimal point and 1 or 2 digits after the decimal point into its own optional group:
将小数点和小数点后的 1 位或 2 位数字组成自己的可选组:
/^\d+(\.\d{1,2})?$/
Tests:
测试:
> var re = /^\d+(\.\d{1,2})?$/
undefined
> re.test('123')
true
> re.test('123.00')
true
> re.test('123.')
false
> re.test('12.34.5')
false
> re.test('123.000')
false
回答by Vivin Paliath
Have you tried:
你有没有尝试过:
/^\d+(\.\d{1,2})?$/
The ?
makes the group (\.\d{1, 2})
optional (i.e., matches 0 or 1 times).
在?
使组(\.\d{1, 2})
可选的(即,匹配0或1次)。
回答by slandau
Would something like this work?
这样的东西会起作用吗?
// Check if string is currency
var isCurrency_re = /^\s*(\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/;
function isCurrency (s) {
return String(s).search (isCurrency_re) != -1
}