Python re.compile() method



The Python re.compile() method is used to compile a regular expression pattern into a regular expression object. This regular expression object can then be used to perform match operations more efficiently as the pattern is only compiled once.

This method takes a string representing the regular expression pattern and optional flags that modify the pattern's behavior such as re.IGNORECASE for case-insensitive matching.

Using re.compile() is beneficial when the same pattern needs to be used multiple times as it avoids the overhead of re-compiling the pattern each time a match operation is performed.

Syntax

Following is the syntax and parameters of Python re.compile() method −

re.compile(pattern, flags=0)

Parameters

The below are the parameters of the python re.compile() method −

  • pattern: The element to be added to the set. This can be any hashable type such as numbers, strings or tuples.
  • flags(optional): A set of flags used to modify the regex behavior. The flags such as re.IGNORECASE, re.MULTILINE.

Return value

This method returns compiled regular expression object.

Example 1

Following is the basic example of python re.compile method.Here the pattern '\d+' which matches one or more digits is compiled and then the match method is used to find the pattern at the beginning of the string −

import re

pattern = re.compile(r'\d+')
match = pattern.match('123abc')
if match:
    print(match.group())  

Output

123

Example 2

Here in this example we specified re.IGNORECASE flag in the re.compile() method which is used to make the pattern case-insensitive −

import re

pattern = re.compile(r'hello', re.IGNORECASE)
match = pattern.match('Hello world')
if match:
    print(match.group())  

Output

Hello

Example 3

This example combinely uses more than one flag in the re.compile() method −

import re

pattern = re.compile(r'^\d+', re.MULTILINE | re.IGNORECASE)
text = """123abc
456def
789ghi"""
matches = pattern.findall(text)
print(matches)  

Output

['123', '456', '789']

Example 4

Here this example uses the re.VERBOSE flag which allows us to write more readable regular expressions with comments and whitespace −

import re

pattern = re.compile(r"""
    \d+     # One or more digits
    \s*     # Zero or more whitespace characters
    """, re.VERBOSE)
matches = pattern.findall('123    abc 456 def')
print(matches)  

Output

['123    ', '456 ']
python_modules.htm
Advertisements