hbsrud
hbsrud

Reputation: 353

Weird Regex Match

I have the following Regex:

Regex.IsMatch(someString, "[1-9][0-9]*\.[0-9]")

I wanted that someString to only allow a form like x.y where x > 0 and 0 <= y <= 9. But it won't work as excepted, an example:

someString = "1.02"
Regex.IsMatch(someString, "[1-9][0-9]*\.[0-9]")

Equals in true, but that can't be I also tried another Regex:

Regex.IsMatch(someString, "[1-9][0-9]*\.[0-9]{1}")

But it made no difference... or is there something missing in my pattern?

Upvotes: 0

Views: 207

Answers (1)

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

You need to use the start-of-line ^ and end-of-line $ anchors here or you will get partial matches like in your case, change to:

^[1-9][0-9]*\.[0-9]$

Your original expression matched a portion of 1.02 which is 1.0 and though it was valid and it is actually valid when taken alone, the anchors prevent the expression from matching partial strings and forces the entire expression to match.

Upvotes: 7

Related Questions