Tuesday, February 10, 2009

.Net Regular Expression for Numbers Range

At work, a colleague asked me for help with with a regular expression he was trying to get working. It was simple and quick and worth a post in my blog.

He wanted to validate for numbers between 1 and 50. After a couple of minutes of testing at http://www.regextester.com/, I sent him this:

Dim re As New Regex("^([0-9]|[0-4][0-9]|[5][0])$")

MsgBox(re.IsMatch(“123”))
MsgBox(re.IsMatch(“2”))
MsgBox(re.IsMatch(“50”))
MsgBox(re.IsMatch(“51”))

3 comments:

Gaz said...

From that Regex ("^([0-9][0-4][0-9][5][0])$") you would only get numbers like:
00050 or 94950

if you wanted numbers between 1 and 59 surely the Regex should be something like:
"^([0-9]|[1-4][0-9]|50)$"

I am not an expert at this, only just started to be honest. Was looking at finding the solution myself and came across your post.

Karthik Padmanabhan said...
This comment has been removed by the author.
Karthik Padmanabhan said...

Oops!

Just realized that the pipe symbol has been stripped off on that post!

Tried adding it again and it would not work when posting from the compose mode. Had to edit my HTML to get that right.

Thank you Gaz, for pointing it out. I drafted the original post in compose mode; I should have obviously reviewed it once.