Regex for number range, and -1

倖福魔咒の 提交于 2021-01-29 17:53:59

问题


I need a regex (Javascript) that allows any positive number between 1 - 2048 (cannot be 0). However it should also allow a single negative number: -1.

After some trial and error I came up with this: ^(-[1]|[1-9]+)$

This allows negative 1 and any number. But being new to regex I'm confused about how to cap the number range to 2048?

Finally, I'm aware that regex is not always recommended. But in this case where there are several conditions(only numbers within a range, no special characters or whitespace, and allow -1), is an if statement preferable?


回答1:


You could use the following regular expression:

^(?:\-1|[1-9]\d{0,2}|1\d{3}|20[0-3]\d|204[0-8])$

though it may easier to use language tools that do not employ a regex or employ a simple regex for part of the verification.

Javascript demo

Javascript's regex engine performs the following operations:

^               # match beginning of string
(?:             # begin a non-capture group
  \-1           # match '-1'
  |             # or
  [1-9]\d{0,2}  # match 1-999
  |             # or  
  1\d{3}        # match 1000-1999
  |             # or
  20[0-3]\d     # match 2000-2039
  |             # or
  204[0-8]      # match 2040-2048
)               # end non-capture group
$               # match end of string

It's easier, however, to use other language tools for determining if the string is a representation of an integer. This is done in three steps:

  • Confirm the string represents an integer (perhaps using a simple regex)
  • Convert the string to an integer
  • Determine if the integer equals a permitted value

In Ruby, for example, this could be done with the following code snippets.

return false unless str.match?(/\A\-?\d+\z/)

x = Integer(str)

x == -1 || (1..2048).cover?(x)

As a bonus, one is left with the integer equivalent. When using a single regex an extra step is required if the integer is needed.




回答2:


try

^(-1|[1-9][0-9]{0,2}|1[0-9]{0,3}|20[0-3][0-9]|204[0-8])$


来源:https://stackoverflow.com/questions/60859339/regex-for-number-range-and-1

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