re.sub() Python RegEx (original) (raw)

Last Updated : 23 Jul, 2025

**re.sub() method in Python parts of a string that match a given regular expression pattern with a new substring. This method provides a powerful way to modify strings by replacing specific patterns, which is useful in many real-life tasks like text processing or data cleaning.

Python `

import re

a = "apple orange apple banana" pattern = "apple" repl = "grape"

Replace all occurrences of "apple" with "grape"

result = re.sub(pattern, repl, a)

print(result)

`

Output

grape orange grape banana

Table of Content

Syntax of re.sub()

re.sub(pattern, repl, string, count=0, flags=0)

Parameters

Return

Using Groups in re.sub()

If regular expression has capture groups****(defined by parentheses())**, we can use the groups in the replacement string using \1,\3,etc., or by using replacement function.

Python `

import re

a = "John 25, Jane 30, Jack 22"

Match name and age

pattern = r"(\w+) (\d+)"

Use age first, then name

repl = r"\2 years old, \1"

Swap names and ages

result = re.sub(pattern, repl, a)

print(result)

`

Output

25 years old, John, 30 years old, Jane, 22 years old, Jack

**Explanation:

Limiting the Number of Replacements

To limit the number of replacements in re.sub(), use the count parameter. By default, **count=0, meaning all occurrences are replaced. Specifying a positive integer limits the number of replacements to that value.

Python `

import re

a = "apple orange apple banana" pattern = "apple" repl = "grape"

Replace only the first occurrence of "apple"

result = re.sub(pattern, repl, a, count=1)

print(result)

`

Output

grape orange apple banana

**Explanation: