Regex matches 2-10 but not 99

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

I have a business rule regarding answers 2-10.

I am trying to write a regex that will match 2-10, but not 99, and I'm having problems.

Original expression:

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

Does not work because 99 matches (technically, twice). In addition, linear boundaries are something that I never liked. I observe different expressions in the expression than in other places (e.g. .net). In this particular case, the regular expression is executed in javascript . In any case, 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 "everything is spelled out" or as a range, expresso never returns any matches if I specify a line / line to close a line / line of a line (and yes, I tried to match 10 separately in the second case).

I know, I know. If you use regex to solve a problem, you have two problems (and presumably they will start inviting friends, style 1 and style 2). I cannot have to use it here; I can go to the description of the case. But it seems to me that I can use a regex here, and that seems like a reasonable deal. I'm still pretty green when it comes to regex;

+7
javascript regex
source share
6 answers

For this you need brackets. I would also use ranges for reading:

 ^([2-9]|10)$ 
+20
source share

This is clearly the case when you should not use RegExp, but a numerical estimate:

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

Use parentheses around alternation, since concatenation takes precedence over alternation:

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

Full javascript function to match either 2, 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 extensible to include all of your rules:

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

edit: I forgot to mention that you have to substitute your true / false situational logic. edit2: added missing bracket for the second regular expression.

+1
source share

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

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

0
source share

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

0
source share

All Articles