Python regex `search` function

Python Regex search() function explained with examples.

The Search Function

The search function searches for first occurance of a re pattern to string with optional flags.

Here is the syntax for this function −

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

Where, pattern is the regular expression to be matched, string is the string to be searched to match the pattern at the beginning of string and flags, which you can specify different flags using bitwise OR (|).

Match Flags

Modifier Description
re.I Performs case-insensitive matching.
re.L Interprets words according to the current locale. This interpretation affects the alphabetic group (\w and \W), as well as word boundary behavior (\b and \B).
re.M Makes $ match the end of a line and makes ^ match the start of any line.
re.S Makes a period (dot) match any character, including a newline.
re.U Interprets letters according to the Unicode character set. This flag affects the behavior of \w, \W, \b, \B.
re.X It ignores whitespace (except inside a set [] or when escaped by a backslash and treats unescaped # as a comment marker.

Return values

  • The re.search function returns a match object on success and None upon failure. -
  • Use group(n) or groups() function of match object to get matched expression, e.g., group(n=0) returns entire match (or specific subgroup n)
  • The function groups() returns all matching subgroups in a tuple (empty if there weren’t any).

Example 1

Let’s find the words before and after the word to:

Get hands-on with 1400+ tech skills courses.