编译一个正则表达式,它将自动转义或忽略特殊字符

2024-10-06 10:23:43 发布

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

我使用一个正则表达式的结果来构建另一个正则表达式,大致如下所示:

regex = '(?P<prev>.+?)(?P<hook>\%\%.+?\%\%)(?P<next>.+?$)'
match = re.search(regex, content, re.S)

comparisonRegex = match.group('prev') + 
    '(?P<desiredContent>desireable)' + match.group('next')
match = re.search(comparisonRegex, otherContent, re.S)

此方法工作正常,但有时会抛出以下错误:

^{pr2}$

我很有信心,这是因为我正在搜索并用作新正则表达式的内容中包含无效字符或序列,但我不确定如何处理这一问题。有没有一个参数我可以传递给它,告诉它把所有字母编译成文字而不是特殊字符?到目前为止,我还没有在python regex guide中找到任何东西。在


Tags: 方法researchmatch错误groupcontenthook
1条回答
网友
1楼 · 发布于 2024-10-06 10:23:43

^{}

regex = '(?P<prev>.?+)(\%\%.+?\%\%)(?P<next>.+?$)'
match = re.search(regex, content, re.S)

comparisonRegex = re.escape(match.group('prev')) + 
    '(?P<desiredContent>desireable)' + re.escape(match.group('next'))
match = re.search(comparisonRegex, otherContent, re.S)

相关问题 更多 >