正则表达式匹配 0 - 999 但不为空 [英] Regex to match 0 - 999 but not blank
问题描述
我正在研究一个正则表达式来匹配有效的整数,例如:
I'm working on a regex to match valid integer numbers such as the following:
- 0
- 1
- 99
- 999
但是它不应该允许匹配空字符串.我能得到的最接近的是:
However it should not allow matching an empty string. The closest I can get is:
(0)|\\d{1,3}
对我来说,匹配的字符串将包含一个零或一系列长度介于 1 到 3 个字符之间的数字.但是,空字符串似乎仍与此模式匹配.从这个正则表达式中排除空字符串的正确方法是什么?
Which to me says a matching string will have either a zero or a series of digits between 1 and 3 characters long. However, empty strings still appear to match this pattern. What's the proper way to exclude empty strings from this regex?
推荐答案
这将匹配(仅)一系列一到三个数字(包括 0 或 00 或 01 或 012 - 不清楚是否需要后者):
This will match (only) a series of one to three numeric digits (including 0 or 00 or 01 or 012 - not clear if those latter ones are desired):
^\d{1,3}$
它不会匹配空字符串(但你原来的复杂表达式也不会).
It will not match empty string (but then neither will your original convoluted expression).
(要允许它作为更大字符串的一部分,请删除 ^
和 $
锚点.)
(To allow this as part of a bigger string, remove the ^
and $
anchors.)
但也许正则表达式在这里不是最佳选择 - 您使用的任何基础语言都没有 isNumeric 函数吗?
But perhaps regex is not best option here - does whatever base language you're using not have an isNumeric function?
要允许 0 但不允许其他以 0 为前缀的数字,您可以使用:
To allow 0 but not other 0-prefixed numbers, you can use:
0|[1-9]\d{0,2}
或者,确保这是整个匹配:
Or, to ensure that's the entire match:
^(?:0|[1-9]\d{0,2})$
这篇关于正则表达式匹配 0 - 999 但不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!