Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Pythonre.compile() method



The Pythonre.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.

Usingre.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 Pythonre.compile() method −

re.compile(pattern, flags=0)

Parameters

The below are the parameters of the pythonre.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 pythonre.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 repattern = re.compile(r'\d+')match = pattern.match('123abc')if match:    print(match.group())

Output

123

Example 2

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

import repattern = 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 there.compile() method −

import repattern = re.compile(r'^\d+', re.MULTILINE | re.IGNORECASE)text = """123abc456def789ghi"""matches = pattern.findall(text)print(matches)

Output

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

Example 4

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

import repattern = 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
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp