这个正则表达式失败了吗,或者我需要修改正则表达式以支持“optional following by”?

2024-05-16 17:42:25 发布

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

我正在尝试以下正则表达式:https://regex101.com/r/5dlRZV/1/,我知道,我正在尝试使用\author,而不是\maketitle

在python中,我尝试以下操作:

import re

text = str(r'
\author{
\small 
}

\maketitle
')

regex = [re.compile(r'[\\]author*|[{]((?:[^{}]*|[{][^{}]*[}])*)[}]', re.M | re.S), 
re.compile(r'[\\]maketitle*|[{]((?:[^{}]*|[{][^{}]*[}])*)[}]', re.M | re.S)]

for p in regex: 
  for m in p.finditer(text): 
     print(m.group())

Python冻结了,我怀疑这与我的模式有关,SRE失败了。你知道吗

编辑:我的正则表达式有问题吗?它能改进到实际工作吗?但我还是在我的机器上得到了同样的结果。你知道吗

编辑2:是否可以以某种方式修复此问题,使模式支持可选的后跟?:或?=看脑袋?这样一个人就能同时抓住这两个?你知道吗


Tags: textinhttpsimportrecom编辑for
1条回答
网友
1楼 · 发布于 2024-05-16 17:42:25

在阅读了这个网站上的标题“括号创建编号的捕获组”后,我设法找到了答案,即:

Besides grouping part of a regular expression together, parentheses also create a 
numbered capturing group. It stores the part of the string matched by the part of 
the regular expression inside the parentheses.

The regex Set(Value)? matches Set or SetValue. 
In the first case, the first (and only) capturing group remains empty. 
In the second case, the first capturing group matches Value.

相关问题 更多 >