正则表达式允许数字和一个点 [英] Regex allow digits and a single dot

查看:57
本文介绍了正则表达式允许数字和一个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

允许数字一个点的正则表达式是什么?关于这个 \D 只允许数字,但它不允许点,我需要它允许数字和 one 点这是指我需要的浮点值在 jQuery 中执行 keyup 函数时有效,但我需要的只是只允许我需要它允许的正则表达式.

What would be the regex to allow digits and a dot? Regarding this \D only allows digits, but it doesn't allow a dot, I need it to allow digits and one dot this is refer as a float value I need to be valid when doing a keyup function in jQuery, but all I need is the regex that only allows what I need it to allow.

这将在 JavaScript 原生的 replace 函数中删除非数字和其他符号(点除外).

This will be in the native of JavaScript replace function to remove non-digits and other symbols (except a dot).

干杯.

推荐答案

如果你想允许 11.2:

If you want to allow 1 and 1.2:

(?<=^| )\d+(\.\d+)?(?=$| )

如果你想允许 11.2.1:

If you want to allow 1, 1.2 and .1:

(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )

如果您只想允许 1.2(仅浮动):

If you want to only allow 1.2 (only floats):

(?<=^| )\d+\.\d+(?=$| )

\d 允许数字(而 \D 允许任何数字).

\d allows digits (while \D allows anything but digits).

(?<=^| ) 检查数字前面是否有空格或字符串的开头.(?=$| ) 确保字符串后跟一个空格或字符串的结尾.这可确保该数字不是另一个数字的一​​部分,也不在单词或任何东西的中间.

(?<=^| ) checks that the number is preceded by either a space or the beginning of the string. (?=$| ) makes sure the string is followed by a space or the end of the string. This makes sure the number isn't part of another number or in the middle of words or anything.

编辑:添加了更多选项,通过添加向前和向后改进正则表达式以确保数字是独立的(即不在单词或其他数字的中间.

Edit: added more options, improved the regexes by adding lookahead- and behinds for making sure the numbers are standalone (i.e. aren't in the middle of words or other numbers.

这篇关于正则表达式允许数字和一个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆