ModuleNotFoundError:没有名为“regex”的模块

问题描述 投票:0回答:1

我是Python新手。我试图使用正则表达式。但我不断收到以下错误:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import regex
ModuleNotFoundError: No module named 'regex'

我的代码:

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.')

我也尝试在一些在线编译器中运行它。但没成功

我不知道为什么会失败。有人可以帮我吗?

python python-3.x regex
1个回答
0
投票

方法一(推荐):

使用内置

re
模块。只需将
regex
替换为
re
即可。

或者,如果您已经编写了相当多的代码,请像这样导入它:

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.')

方法二:

您可以从

pip
安装 regex 模块。并且您现有的代码将正常工作。

在终端中,运行:

python3 -m pip install -U regex

如果它不适合您,请尝试:

python -m pip install -U regex

-U
代表
--upgrade

我还发现了这个问题的3年前的问题

© www.soinside.com 2019 - 2024. All rights reserved.