Python Regular Expressions

  • 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:

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 ExpressionDescriptionSyntaxExample
\dMatches any digitre.search("\d", string)re.search("\d", "The year is 2020")
\DMatches any non-digitre.search("\D", string)re.search("\D", "The year is 2020")
\wMatches any word character (letters, digits, and underscores)re.search("\w", string)re.search("\w", "The car is a Toyota_Camry")
\WMatches any non-word characterre.search("\W", string)re.search("\W", "The car is a Toyota Camry")
\sMatches any white-space characterre.search("\s", string)re.search("\s", "The car is a Toyota Camry")
\SMatches any non-white-space characterre.search("\S", string)re.search("\S", "The car is a Toyota Camry")
[]Matches any character within the square bracketsre.search("[a-z]", string)re.search("[a-z]", "The car is a Toyota Camry")
^Matches the start of a stringre.search("^The", string)re.search("^The", "The car is a Toyota Camry")
$Matches the end of a stringre.search("Camry$", string)re.search("Camry$", "The car is a Toyota Camry")
*Matches zero or more occurrences of the preceding expressionre.search("ca*r", string)re.search("ca*r", "The car is a Toyota Camry")
+Matches one or more occurrences of the preceding expressionre.search("ca+r", string)re.search("ca+r", "The car is a Toyota Camry")
?Matches zero or one occurrence of the preceding expressionre.search("ca?r", string)re.search("ca?r", "The car is a Toyota Camry")
{}Matches a specified number of occurrences of the preceding expressionre.search("\d{4}", string)re.search("\d{4}", "The year is 2020")

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top