4
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$
  • 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
\$\endgroup\$
0
2
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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