Python regex搜索或匹配不起作用

2024-07-03 07:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了这个正则表达式:

 re.search(r'^SECTION.*?:', text, re.I | re.M)
 re.match(r'^SECTION.*?:', text, re.I | re.M)

在这个字符串上运行:

^{pr2}$

我希望得到以下结果:

SECTION 5.01. Financial Statements and Other Information. The Parent\nwill furnish to the Administrative Agent:

但是我得到None作为输出。在

有人能告诉我我做错了什么吗?在


Tags: andthe字符串textresearchinformationmatch
1条回答
网友
1楼 · 发布于 2024-07-03 07:32:28

.*将匹配所有文本,因为文本不是以:结尾的,它返回None。您可以改用反字符类来获得预期结果:

In [32]: m = re.search(r'^SECTION[^:]*?:', text, re.I | re.M)

In [33]: m.group(0)
Out[33]: 'SECTION 5.01. Financial Statements and Other Information. The Parent\nwill furnish to the Administrative Agent:'

In [34]: 

相关问题 更多 >