如何使Python的findall正则表达式方法具有包容性 - python

我有一个字符串,如下所示。

s = 'string with %%substring1%% and %%substring2%%'

我想提取包含%%的子字符串中的文本,但我不知道如何制作包含正则表达式的内容。

例如,re.findall('%%(.*?)%%', s, re.DOTALL)将输出['substring1', 'substring2'],但是我真正想要的是返回['%%substring1%%', '%%substring2%%']

有什么建议么?

python大神给出的解决方案

你已经很近了。将组与整个所需部分匹配,而不是仅将两者之间的字符串匹配

>>> s = 'string with %%substring1%% and %%substring2%%'
>>> import re
>>> re.findall('(%%.*?%%)', s, re.DOTALL)
['%%substring1%%', '%%substring2%%']

您实际上根本不需要paren!

>>> re.findall('%%.*?%%', s, re.DOTALL) # Even this works !!! 
['%%substring1%%', '%%substring2%%']

对于一些可视化,请检查一下

Debuggex Demo

并检查说明here