I would like to create a regex that will validate that a string is an equation made up of a single digits and either the * or + operator and is no longer than 100 characters. So these would be valid:
1+2*3*8+0 9 9*9 And these would not be valid:
1++1 12+1 2*25 1+ 47 + +1 11 I came up with the regex below to accomplish this:
^(d1[+*]1)0,99d$ Which appears to work, but I’m curious if there is a cleaner way to accomplish this. Any suggestions or is this about as clean as it gets?
It is saved here if you would like to play with it.
- While your regex appears to work, it will fail for the condition that your expression should not exceed 100 characters mark. With the boundary of
0,99on a 2 character patternd1[*+]1, you are already expecting a possible expression of length 198 characters. - Using
1quantifier is just redundant. - No need for escaping inside a character set. The only things needing a leading backslash (
) inside a characters list are]and^, where the caret is the only character inside, or the first. - Your expressions will not reach a 100 character mark, unless you allow the
+to act as an unary operator.
Therefore, the following pattern will be the simplest approach (imo)
^(?:d[*+])0,49d$ which is the tiniest bit modified from your original expression.
You can check the pattern in action here on the following expressions:
1+2*3*8+0 9 9*9 1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+5*8 1++1 12+1 2*25 1+ 47 + +1 11 1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+5*8+9 Regex for matching expression that consists of single digit numbers and operators – codereview.stackexchange.com #JHedzWorlD
No comments:
Post a Comment