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;
\d for single or multiple digit numbers To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.
Add the $ anchor. /^SW\d{4}$/ . It's because of the \w+ where \w+ match one or more alphanumeric characters. \w+ matches digits as well.
Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.
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!");
}
You need parantheses for that. I would further use ranges to keep things readable:
^([2-9]|10)$
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With