Regular expressions (or regex for short) are a powerful tool for matching patterns in strings in Python.
The re module provides support for regular expressions in Python. Here are some of the most common functions used in the re module:
re.search(pattern, string): searches for the first occurrence of a pattern in a string.
re.findall(pattern, string): finds all occurrences of a pattern in a string and returns them as a list.
re.sub(pattern, replacement, string): finds all occurrences of a pattern in a string and replaces them with a replacement string.
Here are some examples of how to use regular expressions in Python:
Python:
import re
# search for a pattern in a string
result = re.search(r'hello', 'hello world')
print(result) # output: <re.Match object; span=(0, 5), match='hello'>
# find all occurrences of a pattern in a string
result = re.findall(r'\d+', 'I have 2 cats and 3 dogs')
print(result) # output: ['2', '3']
# replace a pattern in a string with a replacement string
result = re.sub(r'cats', 'birds', 'I have 2 cats and 3 dogs')
print(result) # output: "I have 2 birds and 3 dogs"
In the first example, we use re.search() to search for the pattern "hello" in the string "hello world". The function returns a Match object that contains information about the match.
In the second example, we use re.findall() to find all occurrences of one or more digits in the string "I have 2 cats and 3 dogs". The function returns a list of all the matches found.
In the third example, we use re.sub() to replace all occurrences of the word "cats" with the word "birds" in the string "I have 2 cats and 3 dogs". The function returns the modified string with the replacements made.