Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 286
  • Last Modified:

how to speed up my regex by avoiding backtracking.

Here is a regex, it basically checks for a valid equation, which then goes into my RPN converter. I have very little experience with regular expressions so I'm fairly confident the regex is very inefficient, and I want some suggestions to improve the effeciency.

There is no matching bracket tests in the regex, this is done using stacks prior to the regex test.

Here's the regular expression


As you can see it's very long, but seems to do what I need it to. The equation can have one variable, accepts, sin, cos, tan, ......., allows brackets, etc. Probably fairly straightforward if you trace it out.

Anyway, I have noticed my regex seems quite inefficient, with a simple expression such as this,

regex buddy shows 171 steps in order to find the whole string is a match.

The main problem is when I put very long equations into the regex, it actually goes into a loop sometimes, and I have to end task to the program.

  • 2
1 Solution
You shouldn't use a regular expression for programming language syntax: Use the regex for identifying terms and syntactic elements and a parser for the syntax - that will be much faster (and deterministic!).
adam8Author Commented:
HI, could you please explain in more detail, what's a parser?
adam8Author Commented:
----------You shouldn't use a regular expression for programming language syntax.

The regular expression is for checking if the input is a valid mathematical equation, it has nothing to do with programming language syntax checking...
What I think gabeso is suggesting is that you merely use a regex to check that the expression appears valid at first look; so, each term is seperated by a +, -, /, *, et al.
And that the expression doesn't contain _certain_ characters.

This shouldn't require as much as you have above—something like:


And then use a parser to extract and process each term, etc, and to ensure that the actual data given makes sense.

Just my 2 cents.

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now