Capture Exception Raised by Python Regular Expression



This article gives a guide on how to capture an exception raised by a regular expression in Python. We will also see simple example programs that show how to do this.

Regular expressions are useful for matching patterns in text, but they may result in errors like incorrect syntax or mismatches. Python uses exception handling (try-except) to handle these errors to avoid errors.

For example, if the given pattern is "[a-z", which is an incorrect pattern that can lead to an error showing that the character set is invalid, because the closing bracket ] is missing.

Python Regex Exception Type

The main exception you will face with regex errors is the re.error: It basically shows invalid regex patterns or, other regex-related errors.

How to Catch Regex Exceptions

You can catch the regular expression using the try-catch block as follows -

# Import the re module
import re

try:
   # regex operation
except re.error:
    # handle the error

Now, we will see how you can use a try-catch block to capture an exception raised by Python regex in different scenarios -

Example: Catching an Invalid Regex Pattern

The following example will try to compile an invalid regex pattern. It will try to catch the re.error and print an error message to the console. Here we are using re.compile() function to compile the given regex string.

# Import the re module
import re

# Invalid pattern (missing closing bracket)
pat = "[a-z"  
try:
   re.compile(pat)
except re.error as e:
   print("Regex error:", e) 

Output

This will create the following outcome -

Regex error: unterminated character set at position 0

Example: Matching with Error Handling

This is another easy way to check if there is an error captured in the given regex pattern. So here we will use a valid pattern to see how the try-catch block will handle it in case of any issues.

# Import the re module
import re

try:
    # None is invalid input
    result = re.search("hello", None)  
except re.error as e:
    print("Regex error:", e)

Output

This will generate the following result -

TypeError: expected string or bytes-like object, got 'NoneType'

Example: Handling Multiple Regex Operations

This program runs multiple regex operations for catching exceptions for each. It shows how to handle multiple regex patterns and catch errors for each.

# Import the re module
import re

# Second pattern is invalid
pat = ["[a-z]+", "(", "[0-9]+"]  
for p in pat:
    try:
        re.compile(p)
        print("Pattern compiled:", p)
    except re.error as e:
        print("Error with pattern:", p, "-", e)

Output

This will produce the following result ?

Pattern compiled: [a-z]+
Error with pattern: ( - missing ), unterminated subpattern at position 0
Pattern compiled: [0-9]+

Example: Handling Errors in String Matching

This program tries to handle errors at the time of matching, and it includes invalid regex patterns and input errors. So it basically shows how you can catch errors that occur during the search operation.

# Import the re module
import re

try:
    # Invalid pattern
    pat = "[abc"  
    txt = "abc123"
    match = re.search(pat, txt)
except re.error as e:
    print("Regex error:", e)

Output

This will lead to the following outcome -

Regex error: unterminated character set at position 0
Updated on: 2025-05-26T18:15:13+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements