102 of 151 menu

The search method of the re module

The search method of the re module searches only for the first match with a regular expression. 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.search(regular expression, string, [flags bunting])

Example

Let's find the first substring with numbers using the search method:

txt = 'aaa 123 bbb 456' res = re.search('\d+', txt) print(res)

Result of code execution:

<re.Match object; span=(4, 7), match='123'>

Example

Let's output a match from the Match object:

txt = 'aaaa 123 bbbb 456' res = re.search('\d+', txt) print(res[0])

Result of code execution:

'123'

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 match of module re,
    which looks for a match with a regular expression at the beginning of a line
  • 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