12

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?

1
  • 2
    In terms of pure performance, depends on too many things. But in terms of readability and maintainability, a combination of short regexes is immeasurably superior.
    – user684934
    Mar 16, 2012 at 7:37

3 Answers 3

6

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);
1
  • Also have a look at my blog post: Do you write readable regexes?, where I provide some more details about using RegexOptions.IgnorePatternWhitespace.
    – stema
    Jul 3, 2013 at 19:37
3

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.

1
  • Hang on… How can you talk about compiler optimization when regex is used across many many different languages and systems? Doesn’t your statement depend on which language and which regex library you’re using?
    – Simon East
    Aug 12, 2022 at 0:38
0

Complex regular expressions can be VERY slow, but it depends on your regular expression and your environment. Take the case of string.trim(). It can be trivially implemented with regular expressions. You might use one regex or two (remove front and back whitespace separately). Here is somebody that took 11 different javascript trim implementations and benchmarked them in different browsers: http://blog.stevenlevithan.com/archives/faster-trim-javascript. In that case, one regex loses big time in most situations.

1
  • I realise that your answer is 10 years old, but I would have liked to see some concrete examples of what kind of regex operations are slow. I know that “backtracking” operations can be very slow and CPU intensive with regex. But on the other hand a simple but long statement may not necessarily be slow.
    – Simon East
    Aug 12, 2022 at 0:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.