Python re.sub() Method
re.sub() is a function in the Python re module used toReplace matches.
It finds all matching substrings in a string and replaces them with the specified content.
Word meaning: sub is short for "substitute".
Basic syntax and parameters
Syntax format
re.sub(pattern, repl, string, count=0, flags=0)
Parameter Description
- pattern: The regular expression to match
- repl: The replacement text, which can be a string or a function
- string: The original string
- count: The maximum number of replacements; 0 means replace all
- flags: Regular expression flags
Function description
- Return Value: Returns the new string after replacement.
Example
Example 1: basic replacement
Example
import
re
text
=
"Python is good, Python is great"
Replace Python with Java
result
=
re
.
sub
(
r
'Python'
,
'Java'
,
text
)
(
result
)
Expected output:
Java is good, Java is great
Example 2: replace a specified number of times
Example
import
re
text
=
"Python is good, Python is great"
Replace only the first one
result
=
re
.
sub
(
r
'Python'
,
'Java'
,
text
,
count
=
1
)
(
result
)
Expected output:
Java is good, Python is great
Example 3: replacement with a regular expression
Example
import
re
text
=
"My phone number is 138-1234-5678"
Replace the middle 4 digits of the phone number with ****
result
=
re
.
sub
(
r
'\d{4}'
,
'****'
,
text
)
(
result
)
Expected output:
我的手机号是 138-****-5678
Example 4: use group references
Example
import
re
text
=
"2024-04-02"
Swap the order of year, month and day
result
=
re
.
sub
(
r
'(\d{4})-(\d{2})-(\d{2})'
,
r
'\3/\2/\1'
,
text
)
(
result
)
Expected output:
02/04/2024
Example 5: use a function as the replacement
Example
import
re
text
=
"3 apples, 5 bananas, 8 oranges"
Replace each number with the number + 1
def
add_one
(
match
)
:
return
str
(
int
(
match.
group
(
)
)
1
)
result
=
re
.
sub
(
r
'\d+'
,
add_one
,
text
)
(
result
)
Expected output:
苹果4个,香蕉6个,橙子9个
Python re Module