How to Use Regular Expressions (Regex) in Python?

Regular expressions, or regex, are sequences of characters that define search patterns. In Python, the re module provides support for regular expressions.

Importing the re Module

To use regex in Python, you first need to import the re module:

import re

Basic Regex Functions

Some of the basic functions provided by the re module include:

  • re.match(): Checks for a match at the beginning of a string.
  • re.search(): Searches for a match anywhere in a string.
  • re.findall(): Returns a list of all matches.
  • re.sub(): Replaces matches with a string.

Using re.search()

Example of using re.search():

pattern = r"\bPython\b"
text = "I love Python programming."
match = re.search(pattern, text)
if match:
    print("Match found!")
else:
    print("No match.")

Regex Patterns

Common regex patterns include:

  • \d: Matches any digit.
  • \w: Matches any word character (letters, digits, underscore).
  • \s: Matches any whitespace character.
  • .: Matches any character except a newline.

Example: Validating an Email Address

email_pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
email = "user@example.com"
if re.match(email_pattern, email):
    print("Valid email")
else:
    print("Invalid email")

Using re.sub()

Replace occurrences of a pattern with a specified string:

text = "The rain in Spain"
new_text = re.sub(r"ain", "***", text)
print(new_text)
# Output: The r*** in Sp***

Conclusion

Regular expressions are powerful for pattern matching and text manipulation. By mastering regex in Python, you can perform complex string operations efficiently.

Leave a Reply

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