0

As far as I read, ? is supposed to be the operator to indicate non-greedy(i.e. smallest first) matching in python regex. I am having trouble in relating matching for the following two similar regex strings:

Case 1:

>>> regex = re.compile(r'(Super|Bat|Spider|Ant){1,2}')
>>> regex.search('AntAnt-Man').group()
'AntAnt'
>>> regex = re.compile(r'(Super|Bat|Spider|Ant){1,2}?')
>>> regex.search('AntAnt-Man').group()
'Ant'

Case 2:

>>> regex.search('AntAnt-Man').group()
'AntAnt-Man'
>>> regex = re.compile(r'(Super|Bat|Spider|Ant){1,2}?-(Man)')
>>> regex.search('AntAnt-Man').group()
'AntAnt-Man'

Dilemma: If in case1, group method picks 'Ant' if using ?, why isn't the same happening for case2?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Tarun
  • 11
  • 1

0 Answers0