HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Regex for matching expression that consists of single digit numbers and operators

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
expressionconsistsnumberssinglethatforandregexdigitoperators

Problem

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.

Solution


  • 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

Code Snippets

^(?:\d[*+]){0,49}\d$
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

Context

StackExchange Code Review Q#121959, answer score: 5

Revisions (0)

No revisions yet.