Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I create one complex RegEx or multiple and less complex ones?

Should I create one complex RegEx to tackle all cases on hand or should I break one complex RegEx in multiple Regex which ?

I'm concerned regarding performance using complex Regex. Will breaking the complex Regex into smaller simple regex perform better?

like image 771
Junaid Qadir Shekhanzai Avatar asked Mar 16 '12 07:03

Junaid Qadir Shekhanzai


People also ask

Does compiling regex make it faster?

Regex has an interpreted mode and a compiled mode. The compiled mode takes longer to start, but is generally faster.

Does regex affect performance?

Being more specific with your regular expressions, even if they become much longer, can make a world of difference in performance. The fewer characters you scan to determine the match, the faster your regexes will be.

Why is regex so complicated?

Regular expressions are dense. This makes them hard to read, but not in proportion to the information they carry. Certainly 100 characters of regular expression syntax is harder to read than 100 consecutive characters of ordinary prose or 100 characters of C code.


2 Answers

If you want a meaningful answer to the performance question, you need to benchmark both cases.

Regarding readability/maintainability, you can write unreadable code in any language and so you can do with regular expressions. If you write a big one, be sure to use the x modifier (IgnorePatternWhitespace in c#) and use comments to build your regex.

A randomly chosen example from one of my past answers in c#:

MatchCollection result = Regex.Matches
    (testingString,
        @"       
            (?<=\$)  # Ensure there is a $ before the string
            [^|]*    # Match any character that is not a |
            (?=\|)   #Till a | is ahead
        "
        , RegexOptions.IgnorePatternWhitespace);
like image 82
stema Avatar answered Oct 02 '22 13:10

stema


I don't think there would be much of a difference now because of compiler optimization, however, using a simple one would make understanding your code easier which in turn makes maintenance easier.

like image 32
erogol Avatar answered Oct 02 '22 12:10

erogol