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.
SyntaxFollowing 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 −
This method returns compiled regular expression object.
Example 1Following 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
123Example 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
HelloExample 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4