Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ModuleNotFoundError: No module named 'regex'

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

-U stands for --upgrade

I also found a 3 years old question of the problem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading