python正则模块re中findall和finditer两者相似,但却有很大区别。

区别

  • findall返回list
  • finditer返回一个MatchObject类型的iterator

详细举例介绍

1、findall

在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

注意: match 和 search 是匹配一次, findall 匹配所有。

语法格式为:

findall(string[, pos[, endpos]])

参数:

参数

描述

string

待匹配的字符串。

pos

可选参数,指定字符串的起始位置,默认为 0。

endpos

可选参数,指定字符串的结束位置,默认为字符串的长度。

举例1:

import re

# 查找数字
pattern = re.compile(r'\d+')
# 查找方式1
result1 = pattern.findall('abc 123 bcd 456')

# 查找方式2(在字符串0到8位中查找数字)
result2 = pattern.findall('abc 123 bcd 456', 0, 8)

# 查找方式3,不使用compile
result3 = re.findall(r'\d+','abc 123 bcd 456')

print(result1)
print(result2)
print(result3)

输出

['123', '456']
['123']
['123', '456']

举例2:参数解析程序,实现将命令行各个参数解析出来。

import re

para = 'xcopy /s "c:\\program files" d:\\'

lists = re.findall(r'([^ "]+)|(".+?")', para)
print(lists)
for i in(lists):
    for j in i:
        if j !="":
            print(j.strip('"'))

输出:

[('xcopy', ''), ('/s', ''), ('', '"c:\\program files"'), ('d:\\', '')]
xcopy
/s
c:\program files
d:\
2、finditer

和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。

re.finditer(pattern, string, flags=0)

参数:

参数

描述

pattern

匹配的正则表达式

string

要匹配的字符串。

flags

标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志

举例1:

# -*- coding: UTF-8 -*-
 
import re
 
it = re.finditer(r"\d+","12a32bc43jf3") 
for match in it: 
    print (match.group() )

输出:

12 
32 
43 
3

举例2:参数解析程序,实现将命令行各个参数解析出来。

para = 'xcopy /s "c:\\program files" d:\\'

#匹配[^ "]不在[]中的字符 或者 匹配带引号的字符串
obj = re.finditer(r'([^ "]+)|(".+?")', para)
print(obj)
for i in obj:
    print("groups:",i.groups())
    print(i.group().strip('"'))

输出:

<callable_iterator object at 0x0000000002F2FA20>
groups: ('xcopy', None)
group: xcopy
groups: ('/s', None)
group: /s
groups: (None, '"c:\\program files"')
group: c:\program files
groups: ('d:\\', None)
group: d:\