Python Language Regular Expressions (Regex) Replacing


Replacements can be made on strings using re.sub.

Replacing strings

re.sub(r"t[0-9][0-9]", "foo", "my name t13 is t44 what t99 ever t44")
# Out: 'my name foo is foo what foo ever foo'

Using group references

Replacements with a small number of groups can be made as follows:

re.sub(r"t([0-9])([0-9])", r"t\2\1", "t13 t19 t81 t25")
# Out: 't31 t91 t18 t52'

However, if you make a group ID like '10', this doesn't work: \10 is read as 'ID number 1 followed by 0'. So you have to be more specific and use the \g<i> notation:

re.sub(r"t([0-9])([0-9])", r"t\g<2>\g<1>", "t13 t19 t81 t25")
# Out: 't31 t91 t18 t52'

Using a replacement function

items = ["zero", "one", "two"]
re.sub(r"a\[([0-3])\]", lambda match: items[int(], "Items: a[0], a[1], something, a[2]")
# Out: 'Items: zero, one, something, two'