问题描述
我是新用户,如果这个问题应该在原帖中回答,请原谅:正则表达式匹配大于或等于 20 的数字,以 5 为增量,范围为 20 到 999
I am a new user, so excuse if this question should be answered in it's original post:regex match numbers greater or equal than 20, by increments of 5, range 20 to 999
然而,这是当前的问题:
Neverteless, here is the current question:
- 匹配所有等于或大于 20 的数字(无上限)
- 以 5 为增量
- 无小数点
- 不应允许前导零
使用 stackoverflow 用户 YMI 对另一篇文章的回应:
With stackoverflow user YMI response on another post:
(\d{2}|[2-9])[05]
^([2-9]|[1-9]\d)[05]$
但是我想探索没有上限的选项,也不允许前导零.
However I would like to explorer the option of not having upper limit and the leading zeros not being allowed also.
推荐答案
我的回答和nhahtdh
's 但请注意 \d+
而不是 \d
,它对字符数没有上限.
My answer is very similar to nhahtdh
's but note the \d+
rather than a \d
which places no upper limit on the number of characters.
你会想要一个这样的正则表达式:
You'll want a regex like this:
\b((?:[23456789]|[123456789]\d+)[05])\b
[现场示例]
快速解释这里发生的事情:
To give a quick explanation of what's happening here:
\b
匹配边界,如空格或符号,以便\b
s 会从文本中找到完整的单词- 接下来我们为单词前缀提供两个选项,它可以是一个大于等于 2 的数字:
[23456789]
- 或者可以是 2 个或多个不以 0 开头的数字:
[123456789]\d+
- 对于我们的后缀,我们要求它是 5 的倍数:
[05]
\b
matches a boundary, like a white-space or a symbol so the\b
s will find complete words from the text- Next we give two options for the word prefix, it can be a single number 2 or greater:
[23456789]
- Or it can be 2 or more numbers that are not led by a 0:
[123456789]\d+
- For our suffix we require it to be a multiple of 5:
[05]
顺便说一句,您可以通过简单地消耗 0 然后匹配数字来匹配满足其他条件但也具有前导 0 的数字,注意添加 0*
它将匹配任意数量的前导 0:
Incidentally you can match numbers that meet your other criteria but also posses leading 0s by simply consuming the 0s and then matching the number, note the addition of 0*
which will match any number of leading 0s:
\b0*((?:[23456789]|\d{2,})[05])\b
这篇关于正则表达式 (java) 匹配等于或大于 20、递增 5、不允许前导零的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!