Python学习虫虫

Python | findall()和 finditer()用法

2019-02-24  本文已影响2人  Quora文选

re.findall()

  • findall(string[, pos[, endpos]])
  • 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

实例:

>>> pattern = re.compile(r'\d+')   # 查找数字
>>> result1 = pattern.findall('runoob 123 google 456')
>>> print(result1)
['123', '456']
>>> result2 = pattern.findall('run88oob123google456', 0, 10)
>>> print(result2)
['88', '12']

函数释义:

>>> help(re.findall)
Help on function findall in module re:

findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.
    
    If one or more capturing groups are present in the pattern, return
    a list of groups; this will be a list of tuples if the pattern
    has more than one group.
    
    Empty matches are included in the result.

findall()查询字符串中某个正则表达式模式全部的非重复出现情况。这与 search()在执行字符串搜索时类似,但与 match()和 search()的不同之处在于,findall()总是返回一个列表。

如果 findall()没有找到匹配的部分,就返回一个空列表,但如果匹配成功,列表将包含所有成功的匹配部分(从左向右按出现顺序排列)。

>>> re.findall('car', 'car')
['car']
>>> re.findall('car', 'scary')
['car']
>>> re.findall('car', 'carry the barcardi to the car')
['car', 'car', 'car']

re.finditer()

  • re.finditer(pattern, string, flags=0)
  • 和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。
参数 描述
pattern 匹配的正则表达式
string 要匹配的字符串。
flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志

实例:

>>> it = re.finditer(r'\d+', '12a32bc43jf3')
>>> for match in it:
    print(match.group())
    
12
32
43
3

函数释义:

>>> help(re.finditer)
Help on function finditer in module re:

finditer(pattern, string, flags=0)
    Return an iterator over all non-overlapping matches in the
    string.  For each match, the iterator returns a Match object.
    
    Empty matches are included in the result.

finditer()函数是在 Python 2.2 版本中添加回来的,这是一个与 findall()函数类似但是更节省内存的变体。两者之间以及和其他变体函数之间的差异(很明显不同于返回的是一个迭代器还是列表)在于,和返回的匹配字符串相比,finditer()在匹配对象中迭代。

如下是在单个字符串中两个不同分组之间的差别:

>>> s = 'This and that.'

>>> re.findall(r'(th\w+) and (th\w+)', s, re.I)
[('This', 'that')]
>>> re.finditer(r'(th\w+) and (th\w+)', s,re.I).__next__().groups()
('This', 'that')
>>> re.finditer(r'(th\w+) and (th\w+)', s,re.I).__next__().group(1)
'This'
>>> re.finditer(r'(th\w+) and (th\w+)', s,re.I).__next__().group(2)
'that'
>>> [g.groups() for g in re.finditer(r'(th\w+) and (th\w+)',s, re.I)]
[('This', 'that')]

类似写法:
>>> for g in re.finditer(r'(th\w+) and (th\w+)',s, re.I):
    print(g.groups())
    
('This', 'that')

如下是单个字符串中执行单个分组的多重匹配:

>>> s = 'This and that.'

>>> it = re.finditer(r'(th\w+)', s, re.I)
>>> g = it.__next__()
>>> g.groups()
('This',)
>>> g.group()
'This'
>>> g = it.__next__()
>>> g.groups()
('that',)
>>> g.group(1)
'that'
>>> [g.group(1) for g in re.finditer(r'(th\w+)', s, re.I)]
['This', 'that']

注意:

上一篇下一篇

猜你喜欢

热点阅读