我需要一个匹配以下内容的正则表达式:
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.
更多推荐
正则表达式匹配数字和小数
发布评论