I have a regex as follows /^(\s*\(*\s*[0-9]*\s*[+\-*/]?\s*[0-9]*\s*\)*\s*)*$/
it's not perfect, but it's designed as a fast check that the string being input is a basic math formula, e.g., 7 * 9 * (6 + 5)
. I do secondary checks if this passes to look for unclosed parenthesis (the formula is also allowed to end on an operator).
Javascript's String.prototype.match
is able to use the regex to very quickly match against some strings, e.g., "7 * 912 + 6 + 7 +".match(regex)
- but is very slow against others:
"7 * 912 + 6 + $ +".match(regex)
"7 * 912 + 6 + ^ +".match(regex)
"7 * 912 + 6 + [ +".match(regex)
"7 * 912 + 6 + ] +".match(regex)
It is however fast for: "7 * 912 + $ +".match(regex)
Presumably the reason for this is that the string contains special chars, combined with the ? in the middle (the problem goes away if I remove that) - but only when a certain number of operators are combined? Is there a way to improve the performance of this? Right now I'm just pre-checking for any special chars (since none are allowed anyway) but I'd like something cleaner.