正则表达式只接受正数和小数

编程入门 行业动态 更新时间:2024-10-28 15:34:49
本文介绍了正则表达式只接受正数和小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要javascript中的正则表达式,它只接受正数和小数。这就是我所拥有的,但有些事情是错误的 - 它似乎没有单个正数。

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.

/^[-]?[0-9]+[\.]?[0-9]+$/;

例如, 9 将无效。我怎样才能重构这个,如果至少有一个正数,它会起作用?

For example, 9 will not work. How can I restructure this so if there is at least one positive digit, it will work?

推荐答案

/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/

匹配

0 +0 1. 1.5 .5

但不是

. 1..5 1.2.3 -1

编辑:

要处理科学记数法( 1e6 ),你可能想做

To handle scientific notation (1e6), you might want to do

/^[+]?([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]+)?$/

更多推荐

正则表达式只接受正数和小数

本文发布于:2023-11-10 23:07:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576717.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正数   小数   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!