How to use Python's re.fullmatch() to check if a string matches a given regex pattern

Published on Aug. 22, 2023, 12:13 p.m.

In Python, the re.fullmatch() method can be used to check if a string matches a given regex pattern. This method takes in two arguments, the regex pattern and the string to validate. It returns a Match object if the string matches the regex pattern, or None if there is no match. Here is an example of how to use it:

import re

pattern = r"^\d{5}(?:[-\s]\d{4})?$"
string = "12345"

match = re.fullmatch(pattern, string)
if match:
    print("String matches the regex pattern")
else:
    print("String does not match the regex pattern")

Here are some more examples of using the re.fullmatch() method in Python:

To verify if a string is a valid email address:

import re

pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
string = "[email protected]"

match = re.fullmatch(pattern, string)
if match:
    print("Valid email address")
else:
    print("Invalid email address")

To verify if a string is a valid phone number:

import re

pattern = r"^\d{3}-\d{3}-\d{4}$"
string = "123-456-7890"

match = re.fullmatch(pattern, string)
if match:
    print("Valid phone number")
else:
    print("Invalid phone number")

To match a number, you can use the following regex pattern: \d+. This pattern will match any number of digits, so it will match any number from 0 to infinity. Here is an example of how to use it:

import re

pattern = r"\d+"
string = "The number is 12345"

match = re.search(pattern, string)
if match:
    print("Number found:", match.group(0))

This code will output Number found: 12345, which is the number found in the string.