How you can get a true/false from a Python regular expressions?

The re module provides tools while working with Python's regular expression (regex), which allows us to search for any specific pattern within strings.

Using the re module, we can get True/False results from regular expressions by checking if pattern matching functions return a match object or None. Three main functions help achieve this ?

  • re.match(): Checks if the pattern matches the beginning of the string.

  • re.search(): Scans the entire string to find the first occurrence of the pattern.

  • re.fullmatch(): Checks if the entire string matches the pattern exactly.

Using the re.match() Function

The re.match() function checks if a regular expression matches the beginning of a given string. It returns a Match object if the pattern matches, otherwise returns None.

Example

Let's verify whether a string starts with "hi" using the pattern "^hi". The bool() function converts the result to True or False ?

import re

pattern = r"^hi"
text = "hello world"

match = re.match(pattern, text)

# Evaluates to True if there's a match
is_match = bool(match)  

print("Does text start with 'hi'?", is_match)
Does text start with 'hi'? False

The re.search() method scans through the entire string to find the first occurrence of the pattern anywhere in the string.

Example

Here we search for the word "world" anywhere in the string "hello world" ?

import re

pattern = r"world"
text = "hello world"

match = re.search(pattern, text)

# Evaluates to True if there's a match
is_match = bool(match)  

print("Does text contain 'world'?", is_match)  
Does text contain 'world'? True

Using the re.fullmatch() Function

The re.fullmatch() function attempts to match the entire string against the regular expression pattern. It returns a match object only if the pattern matches the complete string from beginning to end.

Example

Both the string and pattern are exactly "hello world", so re.fullmatch() finds a complete match ?

import re

pattern = r"hello world"
text = "hello world"

match = re.fullmatch(pattern, text)

# Evaluates to True if there's a match
is_match = bool(match) 

print("Does text exactly match pattern?", is_match)
Does text exactly match pattern? True

Comparison of Methods

Method Match Location Use Case
re.match() Beginning only Validating string prefixes
re.search() Anywhere in string Finding pattern occurrence
re.fullmatch() Entire string Complete string validation

Conclusion

Use bool() with regex functions to get True/False results. Choose re.match() for prefix checking, re.search() for pattern finding, and re.fullmatch() for exact string validation.

Updated on: 2026-03-24T19:01:57+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements