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 Compile Regex Pattern using re.compile()

Python Compile Regex Pattern using re.compile()

Updated on: April 2, 2021 | 2 Comments

Python’s re.compile() method is used to compile a regular expression pattern provided as a string into a regex pattern object (re.Pattern). Later we can use this pattern object to search for a match inside different target strings using regex methods such as a re.match() or re.search().

In simple terms, We can compile a regular expression into a regex object to look for occurrences of the same pattern inside various target strings without rewriting it.

Table of contents

  • How to use re.compile() method
    • Example to compile a regular expression
  • Why and when to use re.compile()
    • Is it worth using Python’s re.compile()?

How to use re.compile() method

Syntax of re.compile()

re.compile(pattern, flags=0)Code language: Python (python)
  1. pattern: regex pattern in string format, which you are trying to match inside the target string.
  2. flags: The expression’s behavior can be modified by specifying regex flag values. This is an optional parameter

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

Return value

The re.compile() method returns a pattern object ( i.e., re.Pattern).