正则表达式 - 检查十进制(javascript)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6285119/
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
regex - check for decimal(javascript)
提问by CocaCola
I got this expression from stackoverflow itself - /^\d+(\.\d{0,9})?$/
.
我从 stackoverflow 本身得到了这个表达式 - /^\d+(\.\d{0,9})?$/
。
It takes care of:
它负责:
2
23
23.
25.3
25.4334
0.44
but fails on .23
. Can that be added to the above expression, or something that would take care of all of them?
但失败了.23
。可以将其添加到上述表达式中,或者可以处理所有这些表达式吗?
回答by Ben Roux
This will capture every case you posted as well as .23
这将捕获您发布的每个案例以及 0.23
Limit to 9 decimal places
限制为 9 位小数
var isDecimal = string.match( /^(\d+\.?\d{0,9}|\.\d{1,9})$/ );
No decimal limits:
没有小数限制:
var isDecimal = string.match( /^(\d+\.?\d*|\.\d+)$/ );
回答by Justin Morgan
This covers all your examples, allows negatives, and enforces the 9-digit decimal limit:
这涵盖了您的所有示例,允许否定,并强制执行 9 位小数限制:
/^[+-]?(?=.?\d)\d*(\.\d{0,9})?$/
Live demo: https://regexr.com/4chtk
现场演示:https: //regexr.com/4chtk
To break that down:
分解一下:
[+-]? # Optional plus/minus sign (drop this part if you don't want to allow negatives)
(?=.?\d) # Must have at least one numeral (not an empty string or just `.`)
\d* # Optional integer part of any length
(\.\d{0,9}) # Optional decimal part of up to 9 digits
Since both sides of the decimal point are optional, the (?=.?\d)
makes sure at least one of them is present. So the number can have an integer part, a decimal part, or both, but not neither.
由于小数点的两边都是可选的,因此(?=.?\d)
确保至少存在其中之一。所以数字可以有整数部分、小数部分或两者都有,但不能两者都没有。
One thing I want to note is that this pattern allows 23.
, which was in your example. Personally, I'd call that an invalid number, but it's up to you. If you change your mind on that one, it gets a lot simpler (demo):
我要注意的一件事是这种模式允许23.
,这在您的示例中。就个人而言,我会称其为无效号码,但这取决于您。如果你改变主意,它会变得简单得多(演示):
/^[+-]?\d*\.?\d{1,9}$/
回答by Andrew Hare
Try this expression:
试试这个表达式:
^\d*\.?\d*$
^\d*\.?\d*$