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.

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 5, 2016 at 5:10
\$\endgroup\$

2 Answers 2

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
answered Mar 5, 2016 at 5:41
\$\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.

answered Mar 5, 2016 at 10:40
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.