正则表达式匹配数字和小数

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

我需要一个匹配以下内容的正则表达式:

I need a regex expression that will match the following:

.5 0.5 1.5 1234

但不是

0.5.5 absnd (any letter character or space)

我有这个满足除0.5.5

^[.?\d]+$

推荐答案

这是一项相当常见的任务.我所知道的最简单的处理方法是:

This is a fairly common task. The simplest way I know of to deal with it is this:

^[+-]?(\d*\.)?\d+$

还有其他复杂情况,例如您是否要允许前导零或逗号或类似的东西.这可以像您希望的那样复杂.例如,如果你想允许 1,234,567.89 格式,你可以这样做:

There are also other complications, such as whether you want to allow leading zeroes or commas or things like that. This can be as complicated as you want it to be. For example, if you want to allow the 1,234,567.89 format, you can go with this:

^[+-]?(\d*|\d{1,3}(,\d{3})*)(\.\d+)?\b$

那个 \b 有一个断字,但我把它用作一种偷偷摸摸的方式,要求在字符串的末尾至少有一个数字.这样,空字符串或单个 + 将不匹配.

That \b there is a word break, but I'm using it as a sneaky way to require at least one numeral at the end of the string. This way, an empty string or a single + won't match.

但是,请注意正则表达式不是解析数字字符串的理想方式.我所知道的所有现代编程语言都有快速、简单、内置的方法来做到这一点.

However, be advised that regexes are not the ideal way to parse numeric strings. All modern programming languages I know of have fast, simple, built-in methods for doing that.

更多推荐

正则表达式匹配数字和小数

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

发布评论

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

>www.elefans.com

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