Regular Expression pattern group

JH john.hsu at sovereign.co.nz
Thu Jun 15 08:13:59 CEST 2006


Hi

I am a fussy learner. Could someone explain to me why the following
inconsistency exists between methods? How can it be justified if it is
considered all right?

There are three groups in pattern. However, match object shows 3 groups
in collection, but group has to be indexed from one because the
m.group(0) is the implicit group for whole pattern.

Are these just some things to remember? "Group counting is from one".

>>> p = sre.compile('abc(.(.).)d(ef)')
>>> s
'xxxabc???defxxx'
>>> m = p.search(s)
>>> m.groups()
('???', '?', 'ef')
>>> m.group(0)
'abc???def'
>>> m.group(1)
'???'
>>> m.group(2)
'?'
>>> m.group(3)
'ef'
>>> m.group(4)

Traceback (most recent call last):
  File "<pyshell#279>", line 1, in -toplevel-
    m.group(4)
IndexError: no such group
>>> p.findall(s)
[('???', '?', 'ef')]
>>>




More information about the Python-list mailing list