开发者

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

开发者 https://www.devze.com 2023-02-10 08:55 出处:网络
I want to vali开发者_高级运维date that a text box contains only numbers between 0 and 10. This is the regex I am currently using:

I want to vali开发者_高级运维date 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!


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)$"


^(10|[0-9])

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


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


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.

0

精彩评论

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