Python re.search()和re.findall()之间的区别

Python re.search()和re.findall()之间的区别,python,regex,Python,Regex,以下代码非常奇怪: >>> words = "4324324 blahblah" >>> print re.findall(r'(\s)\w+', words) [' '] >>> print re.search(r'(\s)\w+', words).group() blahblah ()操作符似乎在findall中表现不佳。为什么会这样?我需要一个csv文件 为清晰起见进行编辑:我想使用findall显示blahblah 我发现

以下代码非常奇怪:

 >>> words = "4324324 blahblah"
 >>> print re.findall(r'(\s)\w+', words)
 [' ']
 >>> print re.search(r'(\s)\w+', words).group()
 blahblah
()
操作符似乎在findall中表现不佳。为什么会这样?我需要一个csv文件

为清晰起见进行编辑:我想使用findall显示
blahblah

我发现
re.findall(r'\s(\w+),words)
做了我想做的事,但不知道findall为什么这样对待组

关闭一个字符:

>>> print re.search(r'(\s)\w+', words).groups()
(' ',)
>>> print re.search(r'(\s)\w+', words).group(1)
' '
findall
返回捕获的所有组的列表。你得到了一个空间,因为那是你捕获的。停止捕获,即可正常工作:

>>> print re.findall(r'\s\w+', words)
[' blahblah']

使用模块

如果您希望在正则表达式中保留捕获组,但仍希望查找每个匹配的全部内容而不是组,则可以使用以下选项:

[m.group() for m in re.finditer(r'(\s)\w+', words)]
例如:

>>> [m.group() for m in re.finditer(r'(\s)\w+', '4324324 blahblah')]
[' blahblah']

我想应该是
。组(1)
。对不起,我的问题不清楚,我希望findall的行为像搜索一样,而不是相反。我需要返回“blahblah”。@cornmith:删除分组运算符,然后谢谢:)分组是个问题。编辑:哦,芬德尔就是这么做的!