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
  • 52,115
  • 13
  • 74
  • 94
Lin Ma
  • 9,059
  • 29
  • 91
  • 166

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
  • 441,113
  • 110
  • 1,021
  • 1,148
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,693
  • 2
  • 33
  • 72