开发者

c# regular expression to only allow numbers between 1 and n

开发者 https://www.devze.com 2023-01-04 11:51 出处:网络
I will admit iknow nothing about regular expressions.what I am trying to do is use a variable as part of a regular expression.I want a validation to occur on each character input, which it does, and o

I will admit i know nothing about regular expressions. what I am trying to do is use a variable as part of a regular expression. I want a validation to occur on each character input, which it does, and only allow character between 1 and n, n can be any number from 1 to 999, how do I do that? 1, 2, 3, 开发者_开发问答15, 23, 500 are all valid whereas 003, 0, 3t3 are all invalid.

thanks, R.


I would suggest the following instead, which is analogous to @Doug's answer:

Find a string that starts with 1-9, and is followed by zero, one, or two digits (0-9) and nothing more.

^[1-9][0-9]{0,2}$

This also has the nicety of scaling well if the requirements change, to say 1-9999. In which case, the regex simply becomes:

^[1-9][0-9]{0,3}$


This should do it: ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$

The trick is to think of the problem as a series of digits evaluated one at a time instead of one whole number.

Enjoy!


Are you sure that a regex is the best solution here?

You could use int.TryParse(string, out value)

if this succeeds then ensure that the resultant int is in range...

0

精彩评论

暂无评论...
验证码 换一张
取 消