正则表达式匹配数字和小数 [英] Regex matching numbers and decimals

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

问题描述

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

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.

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

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