Python re.compile() Method

Python re 模块Python re Module


re.compile()is a Pythonremodule function used forcompiling regular expressions.

Precompiling the regular expression pattern into a regular expression object allows it to be reused, improving matching efficiency.

Word Definition: compileIt means compile.


Basic Syntax and Parameters

re.compile()Used to create a compiled regular expression object.

Syntax Format

re.compile(pattern, flags=0)

Parameter Description

  • pattern:
    • Type: string (str)
    • Description: The regular expression pattern to compile.
  • flags:
    • Type: integer (int, optional)
    • Description: Regular expression flags, such asre.IGNORECASE、re.MULTILINEetc. You can use|to combine multiple flags.

Function Description

  • Return value: Returns a compiled regular expression object (re.Patternobject).
  • Features: The compiled object can be reused; compared to callingre.search()functions such as re.match() each time and re-parsing the regular expression, it is more efficient.

Examples

Let's thoroughly master, through a series of examples from simple to complex,re.compile()the usage of re.compile().

Example 1: Basic Usage - Compiling a Regular Expression

Example

import re

# Compile a regular expression
pattern = re.compile(r'\d+')

# Use the compiled object to match
text = "I have 3 apples and 5 oranges"

result = pattern.findall(text)

print("Numbers found:", result)

Expected output:

找到的数字: ['3', '5']

Code explanation:

  1. re.compile(r'\d+')Compile a regular expression that matches one or more digits.
  2. The object returned after compilationpatternhasfindall()、search()、match()methods such as match(), search(), findall(), etc.
  3. Using the compiled object for matching is more efficient.

Example 2: Reusing the Same Pattern Multiple Times

The biggest advantage of compiling a regular expression is that it can be reused, avoiding repeated parsing.

Example

import re

# Compile a regular expression to match email addresses
email_pattern = re.compile(r'\w+@\w+\.\w+')

# Reuse it across multiple texts
texts = [
    "Contact admin@example.com for help",
    "Email: test@test.org",
    "Sender: user@domain.com"
]

for text in texts:
    result = email_pattern.search(text)
    if result:
        print(f"Found email: {result.group()}")

Expected output:

找到邮箱: admin@example.com
找到邮箱: test@test.org
找到邮箱: user@domain.com

Code explanation:

  • Compile the regular expression only once, then reuse it across multiple texts.
  • The compiled object can callsearch()、findall()methods such as search() multiple times.

Example 3: Using Flags

You can specify regular expression flags during compilation to change matching behavior.

Example

import re

# Specify the ignore-case flag during compilation
pattern = re.compile(r'python', re.IGNORECASE)

text = "Python is great, PYTHON is powerful"

# Use the compiled object to search
result = pattern.findall(text)

print("Found:", result)

Expected output:

找到: ['Python', 'PYTHON']

Code explanation:

  • re.IGNORECASEMakes matching case-insensitive.
  • Specifying flags at compile time applies them to all operations using this object.

Example 4: Using Groups

The compiled object can use groups to extract specific content.

Example

import re

# Compile a regular expression using groups
pattern = re.compile(r'(\d{3})-(\d{4})-(\d{4})')

text = "Zhang San: 138-1234-5678, Li Si: 139-9876-5432"

# Find all matches
results = pattern.findall(text)

for result in results:
    print(f"Full: {result)
    print(f" Group 1 (first 3 digits): {result)
    print(f" Group 2 (middle 4 digits): {result)
    print(f" Group 3 (last 4 digits): {result)

Expected output:

完整: 138-1234-5678
  第1组(前3位): 138
  第2组(中间4位): 1234
  第3组(后4位): 5678
完整: 139-9876-5432
  第1组(前3位): 139
  第2组(中间4位): 9876
  第3组(后4位): 5432

Code explanation:

  • Parentheses()create three groups.
  • findall()Returns a list of tuples, each tuple containing the content of the groups.

Example 5: Properties of the Compiled Object

The compiled regular expression object has some useful properties.

Example

import re

# Compile a regular expression
pattern = re.compile(r'\d+', re.IGNORECASE | re.MULTILINE)

print("Pattern:", pattern.pattern)
print("Flags:", pattern.flags)
print("Number of groups:", pattern.groups)
print("Group names:", pattern.groupindex)

Expected output:

模式: \d+
标志: 50
分组数: 1
分组名: {}

Code explanation:

  • pattern.pattern- Returns the original pattern string.
  • pattern.flags- Returns the integer value of the flags.
  • pattern.groups- Returns the number of groups.
  • pattern.groupindex- Returns a dictionary of named groups.

Example 6: Comparison with re Module Functions

Example

import re

text = "ABC123DEF"

# Method 1: Directly use re module functions
result1 = re.search(r'\d+', text)

# Method 2: Compile first, then use the compiled object
pattern = re.compile(r'\d+')
result2 = pattern.search(text)

print("re.search():", result1.group())
print("pattern.search():", result2.group())

# Both methods produce the same result, but the compiled object can be reused

Expected output:

re.search(): 123
pattern.search(): 123

Code explanation:

  • The results of both methods are the same.
  • When you need to use the same pattern multiple times, it is recommended to usere.compile()to compile it in advance.

Python re 模块Python re Module

Other Extensions