Download this code from https://codegive.com
Regular expressions (regex) in Python are a powerful tool for pattern matching and text manipulation. The re module provides the sub function, which allows you to substitute occurrences of a pattern in a string with another string. This tutorial will guide you through using the sub function with multiple patterns.
The re.sub function is part of the re module in Python and is used for string substitution based on regular expressions. It takes three main arguments:
Before diving into multiple patterns, let's first see how to use re.sub with a single pattern.
In this example, the \bworld\b pattern matches the word "world" as a whole word, and it is replaced with "Universe."
To substitute with multiple patterns, you can provide a list of tuples to the re.sub function. Each tuple contains a pattern and its corresponding replacement.
In this example, the input string is transformed by replacing "apple" with "orange," "banana" with "grape," and "cherry" with "strawberry."
Pattern groups allow you to capture parts of the matched pattern for use in the replacement string. You can reference these groups using backreferences (\1, \2, etc.).
In this example, the pattern captures the date and time components separately using groups. The replacement string references these groups to reformat the string.
Here's a complete example combining multiple patterns, groups, and backreferences:
This example substitutes multiple patterns in the input string, transforming it into "The fast red rabbit jumps over the sleepy dog."
Feel free to modify and expand upon these examples based on your specific use case. Regular expressions offer great flexibility, and the re.sub function is a valuable tool for text manipulation in Python.
ChatGPT