Search code examples
javascriptregexnumeric-ranges

Regex to match 2-10, but not 99


I have a field on a form that takes the following values: -1, 2-10, 99

I have a business rule that's concerned with answers 2-10.

I'm trying to write a regular expression that will match 2-10 but not 99, and I'm having trouble.

The original expression:

^2|3|4|5|6|7|8|9|10$

Fails because 99 is matched (technically, twice). Also, the Line boundries are something I've never been comfortable with. I oberve different behavior from them in expresso than I do in other places (e.g. .net). In this particular instance, the regex is being run in javascript. Anyway, expresso seems to ignore them (and if I put the values in brackets:

^[2|3|4|5|6|7|8|9|10]$

^[2-9]$

either "all spelled out" or as a range, expresso never returns any matches if I specify the opening line/string closing line/string characters (and yes, I was trying to match the 10 separately in the second case there).

I know, I know. If you use a regex to solve a problem, then you have two problems (and presumably they'll start inviting friends over, thing 1 and thing 2 style). I don't have to use one here; I may switch to a case statement. But it seems like I should be able to use a regex here, and it seems a reasonable thing to do. I'm still pretty green when it comes to the regex;


Solution

  • You need parantheses for that. I would further use ranges to keep things readable:

    ^([2-9]|10)$