[英]Regular expression for any double type number
I am trying to do the following: 我正在尝试执行以下操作:
myVar = q.match(/[0-9]*\.[0-9]+|[0-9]+/);
However, when I type a decimal, myVar doesn't pick up the decimal until after I type decimal values. 但是,当我键入一个十进制数时,myVar直到我键入十进制值后才选择十进制。
Entered 3, myVar = 3
Entered ., myVar = 3
Entered 3, myVar 3.3
How do I modify this so myVar would equal 3. at the second step? 如何修改此值,以便myVar在第二步等于3。
Thanks. 谢谢。
Don't use the + after [0-9] it means 1 or more occurrence. 不要在[0-9]之后使用+,这表示1次或多次发生。 Try using *.
尝试使用*。 It should work.
它应该工作。
myVar = q.match(/[0-9]*\.[0-9]*|[0-9]*/);
Can be simplified to: 可以简化为:
myVar = q.match(/[0-9]*\.[0-9]*/);
Problem is it is looking for atleast 1 number after the . 问题是它正在寻找至少1个数字。 In your case you want 0 or more.
在您的情况下,您想要0或更大。
It looks like you also want to match something like .3
, right? 看来您也想匹配
.3
,对吗? But you have to be sure your regex doesn't match a decimal point by itself .
但是您必须确保正则表达式本身不匹配小数点
.
. 。 So you could do it with these alternations:
因此,您可以通过以下更改来做到这一点:
myVar = q.match(/\d+\.\d*|\.?\d+/);
\\d+\\.\\d*
matches 3.
, 3.3
, 3.33
etc. \\d+\\.\\d*
匹配3.
, 3.3
, 3.33
等。
\\.?\\d+
matches .3
, .33
, 3
, 33
, etc. \\.?\\d+
匹配.3
, .33
, 3
, 33
,等等。
ALTERNATE: If you need to allow commas for thousands, millions, etc., use the following: 替代:如果需要允许成千上万个逗号,请使用以下命令:
myVar = q.match(/\d{1,3}(,\d{3})*\.\d*|\d{1,3}(,\d{3})*|\.\d+/);
\\d{1,3}(,\\d{3})*\\.\\d*
matches 3.
, 3.3
, 3.33
, 3,333.3
etc. \\d{1,3}(,\\d{3})*\\.\\d*
匹配3.
, 3.3
, 3.33
, 3,333.3
等
\\d{1,3}(,\\d{3})*
matches 3
, 33
, 3,333
etc. \\d{1,3}(,\\d{3})*
匹配3
, 33
, 3,333
等
\\.\\d+
matches .3
, .33
, etc. \\.\\d+
匹配.3
, .33
等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.