0

Wondering in Python 2.7, if I need to use the same regular expression multiple times, to match different content, compile first is always better performance? Thanks.

I show what I mean by below examples,

import re

content = '{(1) hello (1)}'
reg = '{\(1\)(.*?)\(1\)}'
results = re.findall(reg, content)

print results[0]

prog = re.compile(reg)
results = prog.findall(content)

print results[0]

regards, Lin

Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • @niemmi, the answer in the post is for Python 2.5, I am asking Python 2.7. Vote up for your reference. :) – Lin Ma Aug 06 '16 at 06:32
  • 1
    AFAIK, there is no difference between 2.5 and 2.7 in regex handling. If you want to see if there's a difference between explicit & implicit regex compiling for the data you're processing you should perform your own timeit tests. FWIW, I almost always explicitly compile my regexes because I think it makes the code easier to read. – PM 2Ring Aug 06 '16 at 07:07
  • 1
    A thing you should try to improve your pattern is to replace the dot+non-greedy quantifier with something like `[^(]+` if possible. – Casimir et Hippolyte Aug 06 '16 at 09:17
  • @PM2Ring, thanks and vote up. If you could add a reply, I will mark it as answer to benefit people who will have similar issues in the future. – Lin Ma Aug 06 '16 at 23:34
  • @CasimiretHippolyte, thanks for the idea and vote up. I think your regex matches string which is not ends with `(` and with more than one character? I think it is not the same as what I write above. `{\(1\)(.*?)\(1\)}`. At least `+` and `?` are different? If my understanding is wrong, please feel free to correct me. – Lin Ma Aug 06 '16 at 23:35
  • 1
    @LinMa The whole point of closing a question as a duplicate of another question is to consolidate the relevant answers in one place rather than having them scattered all over the site. That makes it easier for people to examine, compare, and vote on those answers. – PM 2Ring Aug 07 '16 at 02:59
  • @PM2Ring, agree. Vote up for your comments. Have a good weekend. – Lin Ma Aug 07 '16 at 04:09

0 Answers0