Regular expressions are a powerful tool for working with text in Python. They allow you to search, match, and manipulate text based on patterns and rules. The re module in Python provides support for regular expressions.
To use regular expressions in Python, you first need to import the re module:
import re
Here are some common functions and methods provided by the re module:
re.match(pattern, string): Attempts to match the pattern at the beginning of the string. Returns a match object if successful, or None otherwise. re.search(pattern, string): Searches the string for the first occurrence of the pattern. Returns a match object if successful, or None otherwise. re.findall(pattern, string): Searches the string for all non-overlapping occurrences of the pattern. Returns a list of matched strings. re.sub(pattern, repl, string): Replaces all occurrences of the pattern in the string with the replacement string repl. Returns the modified string.
Here are some examples of how to use regular expressions in Python:
import re
# match a pattern at the beginning of a string
match = re.match('Hello', 'Hello, World!')
if match:
print('Match found:', match.group())
else:
print('No match found')
# search for a pattern in a string
match = re.search('World', 'Hello, World!')
if match:
print('Match found:', match.group())
else:
print('No match found')
# find all occurrences of a pattern in a string
matches = re.findall('[0-9]+', 'The price is $20 and the discount is 5%')
print('Matches found:', matches)
# replace a pattern in a string
new_string = re.sub('[aeiou]', '*', 'Hello, World!')
print('New string:', new_string)
In this example, we use regular expressions to match a pattern at the beginning of a string, search for a pattern in a string, find all occurrences of a pattern in a string, and replace a pattern in a string.
Regular expressions can be complex and powerful, allowing for advanced text manipulation and processing. The re module provides a range of functions and methods for working with regular expressions in Python.