103 of 151 menu

The match method of the re module

The match method of the re module only searches for a match with a regular expression at the beginning of a string. In the first parameter of the method, we specify the regular expression to search for, and in the second parameter, the string in which to search for it. In the third optional parameter, you can specify flags for additional regular expression settings. The method returns a Match object. If no matches are found, None is returned.

Syntax

import re re.match(regular expression, string, [flags bunting])

Example

Let's find all substrings with numbers:

txt = '123 456 789' res = re.match('\d+', txt) print(res)

Result of code execution:

<re.Match object; span=(0, 3), match='123'>

Example

Now let's make our line start with letter symbols:

txt = 'aaaa 123 456 789' res = re.match('\d+', txt) print(res)

Result of code execution:

None

See also

  • method findall of module re,
    which returns a list of all matches in a string
  • method finditer of module re,
    which returns an iterator of all matches of the regular expression in the string
  • method search of module re,
    which looks for the first match of a regular expression in a string
  • method fullmatch of module re,
    which looks for all matches of a regular expression in a string
  • object Match object of module re,
    which contains information about matches with a regular expression
byenru