re.compile

Full name
re.compile
Library
re
Syntax

re.compile(pattern, flags=0)

Description

The re.compile function creates a regular expression object by compiling a regular expression pattern, which can be used as a matching pattern in the re.match, re.search, etc. functions.

The use of this function makes sense mainly when we want to reuse a search pattern throughout our code, since the previous compilation of the search pattern makes the process more efficient. For example, we can start from the following code that performs a search for the same pattern in two different texts:

re.search(r"(cat)s?", "my cat and your cats are pretty")
<re.Match object; span=(3, 6), match='cat'>
re.search(r"(cat)s?", "my dog and your cats eat a lot")
<re.Match object; span=(16, 20), match='cats'>

This same code could be rewritten by compiling the search pattern only once, and reusing the result in the two searches, resulting in a more efficient approach:

re_obj = re.compile(r'(cat)s?')
re_obj.search('my cat and your cats are pretty')
<re.Match object; span=(3, 6), match='cat'>
re_obj.search('my dog and your cats eat a lot')
<re.Match object; span=(16, 20), match='cats'>
Parameters
  • pattern: Search pattern to compile.
  • flags: Search modifiers.
Result

The re.compile function returns a regular expression object.

Examples

Given the text 'My cat, your dog and my cats are playing', we can search for the presence of the terms 'dog' and 'cat' regardless of whether they are in singular or plural form with the following code:

text = "My cat, your dog and my cats are playing"
pattern = r'dog[s]?|cat[s]?'
re_obj = re.compile(pattern)
re_obj.findall(text)
['cat', 'dog', 'cats']
Submitted by admin on Mon, 05/03/2021 - 09:37