Javascript 正则表达式只接受正数和小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7708333/
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
Regular Expression to accept only positive numbers and decimals
提问by Rich2233
I need a regular expression in javascript that will accept only positive numbers and decimals. This is what I have but something is wrong -- it doesn't seem to take single positive digits.
我需要一个 javascript 中的正则表达式,它只接受正数和小数。这就是我所拥有的,但有些不对劲——它似乎没有取单个正数。
/^[-]?[0-9]+[\.]?[0-9]+$/;
For example, 9
will not work. How can I restructure this so if there is at least one positive digit, it will work?
例如,9
将不起作用。我该如何重组它,以便如果至少有一个正数,它会起作用?
回答by Mike Samuel
/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/
matches
火柴
0
+0
1.
1.5
.5
but not
但不是
.
1..5
1.2.3
-1
EDIT:
编辑:
To handle scientific notation (1e6
), you might want to do
要处理科学记数法 ( 1e6
),您可能需要执行
/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/
If you want strictly positive numbers, no zero, you can do
如果你想要严格的正数,没有零,你可以这样做
/^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$/
回答by Daniel Mendel
There are few different ways to do this depending on your need:
根据您的需要,有几种不同的方法可以做到这一点:
/^[0-9.]+$/
matches 1
and 1.1
but not -1
/^[0-9.]+$/
匹配1
和1.1
,但不-1
/^[0-9]+\.[0-9]+$/
matches 1.1
but not 1
or -1
/^[0-9]+\.[0-9]+$/
匹配1.1
但不匹配1
或-1
Generally, I recommend using a simple regExp reference guide like http://www.regular-expressions.info/for building expressions, and then test them using javascript right your browser console:
通常,我建议使用简单的 regExp 参考指南(如http://www.regular-expressions.info/)来构建表达式,然后在浏览器控制台中使用 javascript 测试它们:
"123.45".match(/^[0-9.]+$/)
"123.45".match(/^[0-9.]+$/)
回答by Mike Christensen
How about like:
怎么样:
^[.]?[0-9]+[.]?[0-9]*$
回答by Ashwin Bhamare
I have found something interesting which work for me!!! hope so for you also...!!!
我发现了一些对我有用的有趣的东西!!!希望你也一样......!!!
[0-9].[0-9]
[0-9] .[0-9]
Regex for accepting only a positive number with a decimal point
正则表达式只接受带小数点的正数
Matches: 1, 2564, 2.5545, 254.555
匹配:1、2564、2.5545、254.555
Not Matches: -333, 332.332.332, 66-665.455, 55554-4552
不匹配:-333、332.332.332、66-665.455、55554-4552
回答by Madhavi Salunke
You can try this -
你可以试试这个——
^\d{0,10}(\.\d{0,2})?$
Also one cool site to test as well as to get description of your own regular expressions https://regex101.com/
也是一个很酷的站点来测试以及获取您自己的正则表达式的描述 https://regex101.com/