Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
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
.
Here is an example of how the error occurs.
# ⛔️ 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.
# ✅ 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.
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.
# 👇️ 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.
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.