Contents
Is regex faster than if else?
2 Answers. Generally, generic programming frameworks (which include using a regex) result in slower code that is faster to write. What a regex library will probably get you is a lot of time saved writing code at the price of an unimportant amount of CPU time.
Is using regex bad?
Regular expressions are powerful tool in programmer’s arsenal, but – there are some cases when they are not a best choice, or even outright harmful. Simple example #1 is parsing HTML with regexp – a known road to numerous bugs. Probably, this also attributes to parsing in general.
Is there a way to optimize regex performance?
It’s trivial to design a finite state machine to accomplish this, and therefore a corresponding regex must exist, but writing it out is not so trivial — and I’d sure hate to have to debug it! Not the answer you’re looking for? Browse other questions tagged regex performance optimization or ask your own question.
Why does regex take so long to run?
Because of the way most regex engines work, it is surprisingly easy to construct a regular expression that can take a very long time to run. In my previous poston regex performance, I discussed why and under what conditions certain regexes take forever to match their input.
How to speed up regex replacement in Python 3?
One thing you can try is to compile one single pattern like “\\b (word1|word2|word3)\\b”. Because re relies on C code to do the actual matching, the savings can be dramatic. As @pvg pointed out in the comments, it also benefits from single pass matching.
Which is faster, single pass matching or regex?
As @pvg pointed out in the comments, it also benefits from single pass matching. If your words are not regex, Eric’s answer is faster. Use this method (with set lookup) if you want the fastest solution. For a dataset similar to the OP’s, it’s approximately 2000 times faster than the accepted answer.