Javascript:允许正负浮点数的正则表达式吗? [英] Javascript: Regular expression to allow negative and positive floating point numbers?
问题描述
我正在尝试编写一个正则表达式以匹配任意长度字符的正浮点和负浮点.我尝试过了
I'm trying to write a regular expression to match both positive and negative floating points of any length of characters. I tried this
/^-|[0-9\ ]+$/
但是这仍然是错误的,因为例如它可以匹配"46.0"和"-46.0",但也可以匹配"4-6.0",这是我不想要的.
However this is still wrong because for example it would match "46.0" and "-46.0" but will also match "4-6.0" which I don't want.
此刻我正在使用
/^-|[0-9][0-9\ ]+$/
这可以解决第一个问题,但可以匹配"-4g"之类的东西,这也是不正确的.
This fixes the first problem but this will match something like "-4g" and that is also incorrect.
我可以使用什么表达式来匹配负浮点数和正浮点数?
What expression can I use to match negative and positive floating points?
推荐答案
为什么没有以下内容?
parseFloat(x) === x
如果您真的想要正则表达式,则有互联网上的整个页面这个任务.他们的结论:
If you really want a regex, there are entire pages on the internet dedicated to this task. Their conclusion:
/^[-+]?[0-9]*\.?[0-9]+$/
或
/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/
如果要允许使用指数表示法.
if you want to allow exponential notation.
这篇关于Javascript:允许正负浮点数的正则表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!