Python re.sub() Method

Python re 模块Python re Module


re.sub()is Pythonremodule function forreplacing matched items.

It finds all matching substrings in the string and replaces them with the specified content.

Word Meaning: subis the abbreviation for substitute (replace).


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.

Examples

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)

print(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)

print(result)

Expected output:

Java is good, Python is great

Example 3: Replace Using 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)

print(result)

Expected output:

我的手机号是 138-****-5678

Example 4: Using 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)

print(result)

Expected output:

02/04/2024

Example 5: Using a Function as Replacement Content

Example

import re

text = "3 apples, 5 bananas, 8 oranges"

# Replace numbers with number + 1
def add_one(match):
    return str(int(match.group()) + 1)

result = re.sub(r'\d+', add_one, text)

print(result)

Expected output:

苹果4个,香蕉6个,橙子9个

Python re 模块Python re Module

Other Extensions