re.search() 和 re.findall() 的区别 [英] Difference between re.search() and re.findall()

查看:77
本文介绍了re.search() 和 re.findall() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码很奇怪:

 >>>字 = "4324324 blahblah">>>打印 re.findall(r'(\s)\w+', words)[' ']>>>打印 re.search(r'(\s)\w+', words).group()废话

() 操作符似乎在 findall 中表现不佳.为什么是这样?我需要它作为 csv 文件.

为清晰起见进行我想使用 findall 显示 blahblah.

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

解决方案

关闭一个字符:

<预><代码>>>>打印 re.search(r'(\s)\w+', words).groups()(' ',)>>>打印 re.search(r'(\s)\w+', words).group(1)' '

findall 返回捕获的所有组的列表.你得到了一个空间,因为那是你捕捉到的.停止捕获,它工作正常:

<预><代码>>>>打印 re.findall(r'\s\w+', words)['blahblah']

使用 csv 模块

The following code is very strange:

 >>> words = "4324324 blahblah"
 >>> print re.findall(r'(\s)\w+', words)
 [' ']
 >>> print re.search(r'(\s)\w+', words).group()
 blahblah

The () operator seems to behave poorly with findall. Why is this? I need it for a csv file.

Edit for clarity: I want to display blahblah using findall.

I discovered that re.findall(r'\s(\w+)', words) does what I want, but have no idea why findall treats groups in this way.

解决方案

One character off:

>>> print re.search(r'(\s)\w+', words).groups()
(' ',)
>>> print re.search(r'(\s)\w+', words).group(1)
' '

findall returns a list of all groups captured. You're getting a space back because that's what you capture. Stop capturing, and it works fine:

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

Use the csv module

这篇关于re.search() 和 re.findall() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆