Python re.compile() Method
re.compile() is a function in the Python re module used tocompile regular expressions.
Pre-compile a regular expression pattern into a regular expression object that can be reused, improving matching efficiency.
Word meaning: compile means "to 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 as
re.IGNORECASE、re.MULTILINE, etc. Multiple flags can be combined using|.
Function description
- Return Value: Returns a compiled regular expression object (a
re.Patternobject). - Feature: The compiled object can be reused, which is more efficient than re-parsing the regular expression on every call to functions such as
re.search().
Example
Let us thoroughly master re.compile() through a series of examples from simple to complex.
Example 1: basic usage - compile a regular expression
Example
import
re
Compile a regular expression
pattern
=
re
.
compile
(
r
'\d+'
)
Match using the compiled object
text
=
"I have 3 apples and 5 oranges"
result
=
pattern.
findall
(
text
)
(
"Numbers found:"
,
result
)
Expected output:
找到的数字: ['3', '5']
Code analysis:
re.compile(r'\d+')Compile a regular expression that matches one or more digits.- The compiled
patternobject hasfindall()、search()、match()and similar methods. - Matching with the compiled object is more efficient.
Example 2: reusing the same pattern
The biggest advantage of compiling a regular expression is that it can be reused, avoiding repeated parsing.
Example
import
re
Compile a regular expression that matches 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:
(
f
"Email found: {result.group()}"
)
Expected output:
找到邮箱: admin@example.com
找到邮箱: test@test.org
找到邮箱: user@domain.com
Code analysis:
- Compile the regular expression only once, then reuse it across multiple texts.
- The compiled object can be called many times with
search()、findall()and similar methods.
Example 3: using flags
Regular expression flags can be specified at compile time to change matching behavior.
Example
import
re
Specify the ignore-case flag at compile time
pattern
=
re
.
compile
(
r
'python'
,
re
.
IGNORECASE
)
text
=
"Python is great, PYTHON is powerful"
Search using the compiled object
result
=
pattern.
findall
(
text
)
(
"Found:"
,
result
)
Expected output:
找到: ['Python', 'PYTHON']
Code analysis:
re.IGNORECASEMakes the match case-insensitive.- When flags are specified at compile time, all operations using this object apply those flags.
Example 4: using groups
The compiled object can use groups to extract specific content.
Example
import
re
Compile a regular expression with 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:
(
f
"Full: {result[0]}-{result[1]}-{result[2]}"
)
(
f
" Group 1 (first 3 digits): {result[0]}"
)
(
f
" Group 2 (middle 4 digits): {result[1]}"
)
(
f
" Group 3 (last 4 digits): {result[2]}"
)
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 analysis:
- Parentheses
()create three groups. findall()Returns a list of tuples, each containing the contents of each group.
Example 5: attributes of the compiled object
A compiled regular expression object has several useful attributes.
Example
import
re
compile regular expressions
pattern
=
re
.
compile
(
r
'\d+'
,
re
.
IGNORECASE
|
re
.
MULTILINE
)
(
"Pattern:"
,
pattern.
pattern
)
(
"Flags:"
,
pattern.
flags
)
(
"Number of groups:"
,
pattern.
groups
)
(
"Group names:"
,
pattern.
groupindex
)
Expected output:
模式: \d+
标志: 50
分组数: 1
分组名: {}
Code analysis:
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 the dictionary of named groups.
Example 6: comparison with re module functions
Example
import
re
text
=
"ABC123DEF"
Method 1: use the re module functions directly
result1
=
re
.
search
(
r
'\d+'
,
text
)
Method 2: compile first, then use the compiled object
pattern
=
re
.
compile
(
r
'\d+'
)
result2
=
pattern.
search
(
text
)
(
"re.search():"
,
result1.
group
(
)
)
(
"pattern.search():"
,
result2.
group
(
)
)
Both methods give the same result, but the compiled object can be reused
Expected output:
re.search(): 123
pattern.search(): 123
Code analysis:
- The results of the two methods are identical.
- When the same pattern is needed many times, it is recommended to use
re.compile()to pre-compile it.
Python re Module