Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么re.match/re.search起作用,而re.findall不起作用';不行?_Python_Regex - Fatal编程技术网

Python 为什么re.match/re.search起作用,而re.findall不起作用';不行?

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

我使用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_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)))