I’m new to python. I was trying to use regex. But I keep getting the following error:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import regex
ModuleNotFoundError: No module named 'regex'
My Code:
import regex
# Define the pattern
pattern = r'Hello, \w+!'
# Create a sample string
string = 'Hello, John!'
match = regex.match(pattern, string)
if match:
print('Pattern matched!')
else:
print('Pattern not found.')
I tried running it in some online compilers too. But didn’t work
I don’t know why this is failing. Can someone please assist me on this?
>Solution :
Method 1 (Recommended):
Use the build-in re module. Just replace regex with re and you are good to go.
Or, if you have written quite a bit of code already, import it like: import re as regex
import re as regex
# Define the pattern
pattern = r'Hello, \w+!'
# Create a sample string
string = 'Hello, John!'
match = regex.match(pattern, string)
if match:
print('Pattern matched!')
else:
print('Pattern not found.')
Method 2:
You can install the regex module from pip. And your existing code will work fine.
In your terminal, run: python3 -m pip install -U regex
If it doesn’t work for you, try: python -m pip install -U regex
-Ustands for--upgrade
I also found a 3 years old question of the problem.