regex (java) match numbers equal or greater than 20, incremented by 5, no leading zeros allowed

二次信任 提交于 2019-12-13 04:53:22

问题


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:

  • Match all numbers equal or greater then 20 (no upper limit)
  • Increments of 5
  • No decimal point
  • Leading zeros shouldn't be allowed

With stackoverflow user YMI response on another post:

(\d{2}|[2-9])[05]

and user nhahtdh

^([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.


回答1:


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

[Live Example]

To give a quick explanation of what's happening here:

  • \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]


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


来源:https://stackoverflow.com/questions/33670681/regex-java-match-numbers-equal-or-greater-than-20-incremented-by-5-no-leadin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!