i

Python Programming

The match function

This Is for : to match RE pattern to string with optional flags.

Here is syntax for this function −

re.match(pattern,string,flags=0)

Here is the description of parameters:

Parameter & Description

 pattern

This is regular expression to be matched.

string

This is string, which would be searched to match pattern at beginning the string.

Flags:

You can use different flags using bitwise(OR (|).The re.match function returns match object on success, None on failure. We usegroup(num) or groups() function of the match object to get matched expression.

Match Object Method / Description

group(number=0)

It returns entire match (or specific subgroup num)

Groups()

It returns all the matching subgroups in a tuple (empty if there weren't any)

Example

Live Demo

Output:

match.group() :  Cats are smarter than dogs

matchObj.group(1) :  Cats

match.group(2) :  smarter