re.sub() - Python RegEx

Last Updated : 6 Oct, 2026

re.sub() function in Python is used to replace occurrences of a regular expression pattern in a string with a specified replacement. It is useful for text cleaning, formatting, and replacing matching patterns in strings.

Syntax

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

Parameters:

  • pattern: The regular expression pattern to search for in the input string.
  • repl: The replacement string or a function that generates replacement text.
  • string: The input string in which replacements are performed.
  • count: The maximum number of replacements. Its default value is 0, which replaces all matching occurrences.
  • flags: Optional modifiers that change the matching behavior, such as case-insensitive matching.

Basic Usage of re.sub()

Following example replaces every occurrence of a specified word in a string.

Python
import re

text = "apple orange apple banana"

result = re.sub("apple", "grape", text)

print(result)

Output
grape orange grape banana

Explanation:

  • Pattern searches for every occurrence of apple in the input string.
  • Each match is replaced with grape, and the resulting string is stored in result.

Replacing Patterns

Unlike ordinary substring replacement, re.sub() can match patterns containing digits, whitespace, and other character classes. This makes it useful for cleaning and normalizing text.

Example:

Python
import re

text = "Python\t\tRegex\nin   Action"

result = re.sub(r"\s+", " ", text)

print(result)

Output
Python Regex in Action

Explanation:

  • Pattern \s+ matches one or more consecutive whitespace characters, including spaces, tabs, and newline characters.
  • Each matching sequence is replaced with a single space, producing normalized text.

Limiting the Number of Replacements

Count parameter specifies how many matches should be replaced. By default, re.sub() replaces every non-overlapping match. Setting count to a positive integer limits the number of substitutions.

Example:

Python
import re

text = "apple orange apple banana apple"

result = re.sub(r"apple", "grape", text, count=1)

print(result)

Output
grape orange apple banana apple

Explanation:

  • count=1 argument restricts the operation to the first matching occurrence.
  • Remaining occurrences are left unchanged.

Using Capture Groups

It allow specific parts of a matched pattern to be reused in the replacement string. Parentheses define these groups, and numbered or named references can rearrange the captured text.

Example:

Python
import re

text = "2026-09-30"

result = re.sub(
    r"(\d{4})-(\d{2})-(\d{2})",
    r"\g<3>/\g<2>/\g<1>",
    text
)

print(result)

Output
30/09/2026

Explanation:

  • Three capture groups represent the year, month, and day, respectively.
  • Replacement string rearranges them into day/month/year format using explicit group references.

Using a Function as the Replacement

repl parameter can accept a function instead of a fixed string. The function receives a match object and returns the replacement text, allowing each match to be transformed dynamically.

Example:

Python
import re

def double_number(match):
    return str(int(match.group()) * 2)

text = "There are 12 apples and 7 oranges."

result = re.sub(r"\d+", double_number, text)

print(result)

Output
There are 24 apples and 14 oranges.

Explanation:

  • Regular expression \d+ identifies one or more consecutive digits, while the function retrieves each matched number.
  • Function doubles each number and returns it as a string, which replaces the corresponding match.

Using Flags with re.sub()

Flags modify how a regular expression matches text. For example, re.IGNORECASE enables case-insensitive matching, allowing the pattern to match uppercase and lowercase variations.

Example:

Python
import re

text = "Python python PYTHON"

result = re.sub(
    r"python",
    "Java",
    text,
    flags=re.IGNORECASE
)

print(result)

Output
Java Java Java

Explanation:

  • re.IGNORECASE flag makes the pattern match Python regardless of capitalization.
  • All three matching occurrences are replaced with Java.

Difference Between re.sub() and str.replace()

Both methods replace text in a string, but they serve different purposes.

re.sub()

str.replace()

Uses regular expression patterns.

Uses exact substring matching.

Supports pattern-based matching and dynamic replacements.

Replaces occurrences of a specified substring.

Accepts regex flags and a replacement function.

Accepts a replacement string and an optional count.

Comment