Python 为什么re.match/re.search起作用,而re.findall不起作用';不行?
我使用re.match查找如下字符串:Python 为什么re.match/re.search起作用,而re.findall不起作用';不行?,python,regex,Python,Regex,我使用re.match查找如下字符串: print(re.match('''#include(\s)?".*"''', '''#include "my.h"''')) <_sre.SRE_Match object; span=(0, 15), match='#include "my.h"'> 然后我得到了这样的结果: print(re.match('''#include(\s)?".*"''', '''#include "my.h"''')) <_sre.SRE_Matc
print(re.match('''#include(\s)?".*"''', '''#include "my.h"'''))
<_sre.SRE_Match object; span=(0, 15), match='#include "my.h"'>
然后我得到了这样的结果:
print(re.match('''#include(\s)?".*"''', '''#include "my.h"'''))
<_sre.SRE_Match object; span=(0, 15), match='#include "my.h"'>
结果是:
[' ']
我很困惑,为什么不re.findall
返回匹配的字符串?我的正则表达式出了什么问题?来自帮助(re.findall)
:
返回字符串中所有非重叠匹配项的列表
如果模式中存在一个或多个捕获组,则返回
小组名单;如果模式中包含更多的元组,则这将是元组列表
不止一组
结果中包含空匹配项
括号中的位,(\s)
,是一个捕获组,所以re.findall
返回捕获列表。只有一个捕获组,因此列表中的每个项都只是一个字符串,而不是一个元组
您可以使用?:
,即(?:\s)?
,使组不捕获。不过,这在当时不是很有用,因为它只相当于\s?
。为了获得更大的灵活性–例如,如果您需要捕获多个零件–re.finditer
可能是最好的方法:
for m in re.finditer(r'#include\s*"(.*?)"', '#include "my.h"'):
print('Included %s using %s' % (m.group(1), m.group(0)))