laura
laura

Reputation: 2961

Regex: Why doesn't @"^([0-9]|10)" match '10'?

I want to validate that a text box contains only numbers between 0 and 10.

This is the regex I am currently using:

@"^([0-9]|10)"

But it only matches 0-9. What should I change to make it match 10??

Thanks!

Upvotes: 1

Views: 7953

Answers (4)

hungryMind
hungryMind

Reputation: 6999

Use this @"^(10|[0-9])". Other way it will treat 1 of 10 as first match from first condition and so does not fall on OR condition.

Upvotes: 0

Ryan Kinal
Ryan Kinal

Reputation: 17732

It might be "lazy", matching the first potential match, i.e. "1" vs. "10". Perhaps try switching the order:

"^(10|[0-9])"

This means the regex will check for '10' first, and will check for [0-9] only if there is no '10'

If that doesn't work, there may be a flag you can

Upvotes: 1

Julian
Julian

Reputation: 36740

^(10|[0-9])

Because the [0-9] was first matching the 1 of the 10.

Upvotes: 2

Bart Kiers
Bart Kiers

Reputation: 170158

The 1 from 10 is matched by [0-9] because the regex engine matches from left to right. And since you only anchored the beginning-of-input : ^, the engine is satisfied if the 1 is matched.

There are two solutions.

1 - Swap it:

@"^(10|[0-9])"

or

2 - anchor it with $:

@"^([0-9]|10)$"

Upvotes: 15

Related Questions