Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Replace matches with a compiled regex using re.Pattern.sub

Call `sub()` on a compiled regular expression to replace matches with a template or a function’s result. Use `count` to limit the number of replacements.

Version: Python 3.12

Syntax

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

In Python 3.12, re.Pattern.sub is a method of the object returned by re.compile(). Call it as pattern.sub(repl, string, count=0). Unlike the module-level function re.sub(), the method takes neither a separate pattern nor a flags argument: it uses the pattern and flags already stored in the object. You can reuse the object with different inputs.

The method replaces non-overlapping matches from left to right and returns the result without modifying the input. If nothing matches, it returns the input unchanged. A positive count sets the maximum number of replacements; 0 or omitting it means no limit. An empty match is skipped if it immediately follows another empty match, but it can be replaced immediately after a non-empty match.

A string repl is a template: \g<id> inserts the text captured by the named group id, and \g<0> inserts the entire match. Even r"..." notation does not turn off template processing. For example, \n inserts a newline, and unrecognized escapes consisting of a backslash followed by an ASCII letter are errors.

If repl is a function, the method calls it once per match being replaced, passing one re.Match object. The return value is inserted literally, without template processing. Use this form to insert arbitrary text verbatim rather than using re.escape(), which is for patterns. Do not mix str and bytes across the pattern, input, and replacement value, including a value returned by the function.

Examples

import re

pattern = re.compile(r"sku=(?P<id>[0-9]+)", re.IGNORECASE)
text = "sku=7, SKU=42"


def format_item(match):
    return f"item-{int(match.group('id')):04d}"


print(pattern.sub(r"item-\g<id>", text, count=1))
print(pattern.sub(format_item, text))

Result

item-7, SKU=42
item-0007, item-0042

Both calls reuse the same pattern with `re.IGNORECASE`. The template with `count=1` changes only `sku=7`. The second call starts from the original text again and pads both IDs with zeros to four digits.

Related lessons

  • Python · Lesson 34 · Advanced · Version: 5

Sources