Question

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;

Was it helpful?

Solution

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

^([2-9]|10)$

OTHER TIPS

This is clearly a case where you shouldn't use RegExp but numerical evaluation:

var num = parseInt(aNumber, 10);
if (num >= 2 && num <= 10) {
    alert("Match found!");
}

Use parentheses around the alternations, since concatenation has higher precedence than alternation:

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

A complete javascript function to match either 2 though 9, or 10

<script type="text/javascript">
    function validateValue( theValue )
    {
        if( theValue.match( /^([2-9]{1}|10)$/ ) )
        {
            window.alert( 'Valid' );
        }
        else
        {
            window.alert( 'invalid' );
        }
        return false;
    }
</script>

The regex is easily expanded to incorporate all of your rules:

/^(-1|[2-9]|10|99)$/ // will match -1, 2-10, 99

edit: I forgot to mention you'll have to substitute your own true/false situational logic. edit2: added missing parenthesis to 2nd regex.

The reason your original expression fails is because you're matching ^2, 3, 4, 5, 6, 7, 8, 9, 10$.

Try this regex: ^(2|3|4|5|6|7|8|9|10)$

This online utility is very good at generating re's for numeric ranges: http://utilitymill.com/utility/Regex_For_Range. For the range 2-10 inclusive, it gives this expression: \b0*([2-9]|10)\b. If you want to omit leading 0's, take out the "0*" part.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top