Lin Ma Lin Ma - 4 months ago 17
Python Question

regular expression for shortest match in Python 2.7

I am using Python 2.7. The current code returns

hello }{(2) world
. If I only want the shortest match, in this case
hello
, what is the solution in Python 2.7?

import re

content = '{(1) hello }{(2) world}'
reg = '{\(1\)(.*)}'
results = re.findall(reg, content)
print results[0]

Answer

Make the wildcard match non-greedy:

>>> reg = r'{\(1\)(.*?)}'
# this ? is important^
>>> results = re.findall(reg, content)
>>> print results[0]
 hello