The subject of regular expressions is quite deep, and it takes an immense amount of practice to get used to the special character syntax. Furthermore, the re module contains a vast set of methods available for performing searches using regular expressions. Upon completing the examples in this section, you should have a much deeper appreciation for how powerful regular expressions can be.
Modifying Strings with Patterns
In addition to searching through text,
re supports modifying text using regular expressions as the search mechanism, and the replacements can reference groups matched in the pattern as part of the substitution text. Use
sub() to replace all occurrences of a pattern with another string.
References to the text matched by the pattern can be inserted using the
\num syntax used for back-references.
To use named groups in the substitution, use the syntax
\g<name> syntax also works with numbered references, and using it eliminates any ambiguity between group numbers and surrounding literal digits.
Pass a value to
count to limit the number of substitutions performed.
Only the first substitution is made because
The search pattern matches twice in the example.