Fix - NameError: name 're' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

Fix - NameError: name 're' is not defined in Python #

The Python "NameError: name 're' is not defined" occurs when we use the re module without importing it first. To solve the error, import the re module before using it - import re.

nameerror name re is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 're' is not defined prog = re.compile(r'\w+') result = prog.match('hello world 123') print(result)

To solve the error, we have to import the re module.

main.py
# ✅ import re module first import re prog = re.compile(r'\w+') result = prog.match('hello world 123') print(result)

Even though the re module is in the Python standard library, we still have to import it before using it.

Make sure you haven't used a capital letter r when importing re because module names are case-sensitive.

Also, make sure you haven't imported re in a nested scope, e.g. a function. Import the module at the top level to be able to use it throughout your code.

An alternative to importing the entire re module is to import only the functions and constants that your code uses.

main.py
# 👇️ import only compile function from re module from re import compile prog = compile(r'\w+') result = prog.match('hello world 123') print(result)

The example shows how to only import the compile function from the re module.

Instead of accessing the members on the module, e.g. re.compile, we now access them directly.

This should be your preferred approach because it makes your code easier to read.

For example, when we use an import such as import re, it is much harder to see which functions from the re module are being used in the file.

Conversely, when we import specific functions, it is much easier to see which functions from the re module are being used.

The re module provides regular expression matching operations.

You can view all of the functions the re module provides by visiting the official docs.

Use the search field on my Home Page to filter through my more than 1,000 articles.