Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between groups and group in the re module?

Tags:

python

regex

Here it 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 me nothing, but group(0) yields some? What is the difference?

Follow Up

Code is as follows

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

findall can get me all the -\w+ \w+ substrings, but look at this:

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

Why can't search give me all the substrings?

Follow Up Again

If s = 'abc -j k -l m -k o, and

>>>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
like image 532
Alcott Avatar asked Feb 19 '12 09:02

Alcott


2 Answers

groups() only returns any explicitly-captured groups in your regex (denoted by ( round brackets ) in your regex), whereas group(0) returns the entire substring that's matched by your regex regardless of whether your expression has any capture groups.

The first explicit capture in your regex is indicated by group(1) instead.

Re follow-up edit:

Why can't search give me all the substrings?

search() will only return the first match against the pattern in your input string.

like image 96
BoltClock Avatar answered Oct 05 '22 23:10

BoltClock


Let me explain with a small example

>>> 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'

Explanation: groups() is a tuple type which has all the values which are pattern matched with your regular expression.

groups(0) or groups() or groups(1) .... It only prints all the values

group() or group(0) -> It will give entire string along with the value which is pattern matched with your regular expression.

group(1) will give first pattern matched value

group(2) will give second pattern matched value....

like image 21
Sivaprasad Avatar answered Oct 06 '22 00:10

Sivaprasad