Python Regex: re.match(), re.search(), re.findall() with Example

Created with Sketch.

Regular expressions (regex) are powerful tools for pattern matching in strings. In Python, the re module provides functions like re.match(), re.search(), and re.findall() to work with regular expressions. Here are examples for each:

1. re.match():

re.match() checks for a match only at the beginning of the string:

import re

pattern = r"Hello"
text = "Hello, World!"

match_obj = re.match(pattern, text)

if match_obj:
    print(f"Match found: {match_obj.group()}")
else:
    print("No match found.")

2. re.search():

re.search() searches for the pattern anywhere in the string:

import re

pattern = r"World"
text = "Hello, World!"

search_obj = re.search(pattern, text)

if search_obj:
    print(f"Match found: {search_obj.group()}")
else:
    print("No match found.")

3. re.findall():

re.findall() finds all occurrences of the pattern in the string:

import re

pattern = r"\w+"  # Match one or more word characters
text = "Hello, World! This is a sample text."

matches = re.findall(pattern, text)

if matches:
    print(f"Matches found: {matches}")
else:
    print("No matches found.")

In this example, the pattern r"\w+" matches one or more word characters. The re.findall() function returns a list of all matches.

These are simple examples, and you can create more complex patterns to match specific strings or patterns in your data. Remember to use raw strings (prefixing the pattern with r) when dealing with regular expressions in Python to avoid unintended escape characters.

Leave a Reply

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