且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式 (java) 匹配等于或大于 20、递增 5、不允许前导零的数字

更新时间:2022-11-14 17:45:19

我的回答和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 匹配边界,如空格或符号,以便 \bs 会从文本中找到完整的单词
  • 接下来我们为单词前缀提供两个选项,它可以是一个大于等于 2 的数字:[23456789]
  • 或者可以是 2 个或多个不以 0 开头的数字:[123456789]\d+
  • 对于我们的后缀,我们要求它是 5 的倍数:[05]
  • \b matches a boundary, like a white-space or a symbol so the \bs 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