PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » RegEx » Python Regex Search using re.search()

Python Regex Search using re.search()

Updated on: April 2, 2021 | 1 Comment

Python regex re.search() method looks for occurrences of the regex pattern inside the entire target string and returns the corresponding Match Object instance where the match found.

The re.search() returns only the first match to the pattern from the target string. Use a re.search() to search pattern anywhere in the string.

Table of contents

  • How to use re.search()
  • Regex search example – look for a word inside the target string
    • Regex search example find exact substring or word
  • When to use re.search()
  • Search vs. findall
  • Regex search groups or multiple patterns
    • Search multiple words using regex
  • Case insensitive regex search

How to use re.search()

Before moving further, let’s see the syntax of it.

Syntax

re.search(pattern, string, flags=0)Code language: Python (python)

The regular expression pattern and target string are the mandatory arguments, and flags are optional.

  • pattern: The first argument is the regular expression pattern we want to search inside the target string.
  • string: The second argument is the variable pointing to the target string (In which we want to look for occurrences of the pattern).
  • flags: Finally, the third argument is optional and it refers to regex flags by default no flags are applied.

There are many flags values we can use. For example, the re.I is used for performing case-insensitive searching. We can also combine multiple flags using bitwise OR (the | operator).

Return value

The re.search() method returns a Match object ( i.e., re.Match). This match object contains the following two items.

  1. The tuple object contains the start and end index of a successful match.
  2. Second, it contains an actual matching value that we can retrieve using a group() method.

If the re.search() method fails to locate the occurrences of the pattern that we want to find or such a pattern doesn’t exist in a target string it will return a None type.

Now, Let’s see how to use re.search().