- Python provides a module called
re
that allows you to work with regular expressions. - A regular expression is a pattern that can be used to match, search, and manipulate strings.
Below is a simple example that demonstrates how to use regular expressions in Python:
1 2 3 4 5 6 7 8 9 10 11 12 |
import re car_string = "This is a 2020 Toyota Camry in Red color" # Search for a pattern in the string result = re.search("\d{4}", car_string) # Get the matched string year = result.group() print("Year:", year) |
In this example, we import the re
module and use the re.search
method to search for a pattern in the string car_string
. The pattern "\d{4}"
matches any four consecutive digits. The re.search
method returns a Match
object that contains information about the match. We use the group
method of the Match
object to get the matched string, which is the year of the car.
Here’s a table that lists some common regular expressions and their usage:
Regular Expression | Description | Syntax | Example |
---|---|---|---|
\d | Matches any digit | re.search("\d", string) | re.search("\d", "The year is 2020") |
\D | Matches any non-digit | re.search("\D", string) | re.search("\D", "The year is 2020") |
\w | Matches any word character (letters, digits, and underscores) | re.search("\w", string) | re.search("\w", "The car is a Toyota_Camry") |
\W | Matches any non-word character | re.search("\W", string) | re.search("\W", "The car is a Toyota Camry") |
\s | Matches any white-space character | re.search("\s", string) | re.search("\s", "The car is a Toyota Camry") |
\S | Matches any non-white-space character | re.search("\S", string) | re.search("\S", "The car is a Toyota Camry") |
[] | Matches any character within the square brackets | re.search("[a-z]", string) | re.search("[a-z]", "The car is a Toyota Camry") |
^ | Matches the start of a string | re.search("^The", string) | re.search("^The", "The car is a Toyota Camry") |
$ | Matches the end of a string | re.search("Camry$", string) | re.search("Camry$", "The car is a Toyota Camry") |
* | Matches zero or more occurrences of the preceding expression | re.search("ca*r", string) | re.search("ca*r", "The car is a Toyota Camry") |
+ | Matches one or more occurrences of the preceding expression | re.search("ca+r", string) | re.search("ca+r", "The car is a Toyota Camry") |
? | Matches zero or one occurrence of the preceding expression | re.search("ca?r", string) | re.search("ca?r", "The car is a Toyota Camry") |
{} | Matches a specified number of occurrences of the preceding expression | re.search("\d{4}", string) | re.search("\d{4}", "The year is 2020") |