Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

^(\d{1}[\+\*]{1}){0,99}\d$

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.

share|improve this question
up vote 5 down vote accepted
  • 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,99} on a 2 character pattern \d{1}[\*\+]{1}, you are already expecting a possible expression of length 198 characters.
  • Using {1} quantifier 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,49}\d$

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
share|improve this answer
    
Beautiful - just what I was looking for. Thanks! – Abe Miessler Mar 5 at 6:59

Explicit length check for clarity

You checked the length of the string inside the regular expression, it was not obvious and @hjpotter92 found a bug in it. His fix uses half of the desired length inside the regexp making it even less intuitive.

I suggest using as a regexp ^(?:\d[*+])*\d$ and checking the length separately.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.