How to use regular expressions in Python

1 min

In Python, you can use regular expressions (regex) with the re module.

Here are some basic regex operations in Python:

  1. search: Searches the string for a match to the regex pattern and returns a Match object if there is a match anywhere in the string.
import re

text = "The cat is cute."

match = re.search(r"cat", text)

if match:
    print("Match found!")
  1. findall: Returns a list containing all matches in the string as strings.
import re

text = "The cat is cute. The dog is friendly."

matches = re.findall(r"\w+", text)

print(matches)
# Output: ['The', 'cat', 'is', 'cute', 'The', 'dog', 'is', 'friendly']
  1. sub: Replaces all occurrences of the regex pattern in the string with a specified replacement.
import re

text = "The cat is cute. The dog is friendly."

new_text = re.sub(r"\bcat\b", "dog", text)

print(new_text)
# Output: 'The dog is cute. The dog is friendly.'
  1. split: Splits the string by the occurrences of the regex pattern.
import re

text = "The cat is cute. The dog is friendly."

words = re.split(r"\s+", text)

print(words)
# Output: ['The', 'cat', 'is', 'cute.', 'The', 'dog', 'is', 'friendly.']

These are just some of the basic operations you can perform with regex in Python. You can find more information in the Python documentation: https://docs.python.org/3/library/re.html