I thought that even though a group was optional
>>> import re
>>> s = 'before [5.5s] after'
>>> r = re.compile(r'(5)?.*')
>>> print r.search(s).groups()
>>> r2 = re.compile(r'(5).*')
>>> print r2.search(s).groups()
s, which is a "b", is matched against
(5)?, which doesn't result in a match. That's not a problem, however, because
(5)?is an optional part of the pattern, so the regex engine matches it zero times and keeps advancing the current position in the pattern.
(5)itself, however, didn't match anything, so you're seeing the
Nonein your first example.
5is no longer optional, so the first character of a potentially matching string has to be a "5". Therefore, a potential match starts at the "5" after "before [".
.*, which it does.
Note that in general, using the greedy
.* is almost never what you want.