What is the difference between groups and group in re module?

There he is:

import re
>>>s = 'abc -j k -l m'
>>>m = re.search('-\w+ \w+', s)
>>>m.groups()
()
>>> m.group(0)
'-j k'

Why groups()gives nothing, but group(0)gives some? What is the difference?

Follow up

The code is as follows

>>>re.findall('(-\w+ \w+)', s)
['-j k', '-l m', '-n o']

findallcan get all the substrings -\w+ \w+, but look at this:

>>>m = re.search('(-\w+ \w+)+', s)
>>>m.groups()
('-j k',)

Why searchcan't give me all the substrings?

Repeat again

If s = 'abc -j k -l m -k oand

>>>m = re.search(r'(-\w+ \w+ )+', s)
>>>m.groups()
('-l m ',)      # why just one substring?
>>>m.group(0)
'-j k -l m '    # as I expected
+5
source share
3 answers

groups()returns only any explicitly captured groups in your regular expression (indicated (by parentheses )in your regular expression), while it group(0)returns the entire substring that matches your regular expression, regardless of whether your expression has any capture groups.

group(1) .

:

search ?

search() .

+11

>>> var2 = "Welcome 44 72"
>>> match = re.search(r'Welcome (\d+) (\d+)',var2)
>>> match.groups()
('44', '72')
>>> match.groups(0)
('44', '72')
>>> match.groups(1)
('44', '72')
>>> match.group(0)
'Welcome 44 72'
>>> match.group(1)
'44'

: groups() - , , .

groups(0) groups() groups(1)....

group() group (0) → , .

(1)

(2) ....

+2

, parens ((...)).

+1

All Articles