0

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]
khelwood
  • 55,782
  • 14
  • 81
  • 108
Lin Ma
  • 9,739
  • 32
  • 105
  • 175

2 Answers2

3

Make the wildcard match non-greedy:

>>> reg = r'{\(1\)(.*?)}'
# this ? is important^
>>> results = re.findall(reg, content)
>>> print results[0]
 hello 
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

For this kind of situation negated character class will also help you.

reg = r'{\(1\)([^}]*)}'

results = re.findall(reg, content)

print results[0]
mkHun
  • 5,891
  • 8
  • 38
  • 85