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

前端 未结 3 738
情歌与酒
情歌与酒 2021-02-06 01:11

Here it is:

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


        
3条回答
  •  孤独总比滥情好
    2021-02-06 02:00

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

提交回复
热议问题