re模块 match serach findall 详解

时间:2022-06-01 19:28:23

re.match

#coding:utf-8
#从首字母开始匹配,匹配一次就结束
import re
s= '23432werwre2342werwrew'
p = r'(\d*)([a-zA-Z]*)'
m = re.match(p,s)
print(m.group()) #返回所有匹配内容 23432werwre
print(m.group(0)) #和group()一样 23432werwre
print(m.group(1)) #返回字串第一个 23432,没有字串则报错
print(m.group(2)) #返回字串第二个 werwre
print(m.groups()) #返回所有字串组成的元组 ('23432', 'werwre'),如果没有字串则为空元组


字串排序:

#coding:utf-8
#从左向右匹配
import re
s= 'abcd'
p = r'((a(b))(c(d)))'
m = re.search(p,s)
print(m.group()) #abcd
print(m.group(1)) #abcd
print(m.group(2)) #ab
print(m.group(3)) #b
print(m.group(4)) #cd
print(m.group(5)) #d
print(m.groups()) #('abcd', 'ab', 'b', 'cd', 'd')

结论:

1  2  3    4  5

(   (  ())   (  ()) )


re.search():和re.match一样,只是re.search不是从首字母开始匹配


re.findall():也不是从首字母开始匹配,但是会匹配所有而不是只匹配一次,返回一个列表

1)如果正则表达式里有(),则列表里的元素为元组,每一个元组包含所有的字串。

2)如果正则表达式里没有(),则列表里的每个元素都是字符串,字符串为所有匹配到的内容.

#coding:utf-8
import re

s = 'abc def ghi 123 456 789'
l= re.findall(r'((\w+)\s+\w+)',s)
print(l)
#[('abc def', 'abc'), ('ghi 123', 'ghi'), ('456 789', '456')]

l = re.findall(r'(\w+)\s+(\w+)',s)
print(l)
#[('abc', 'def'), ('ghi', '123'), ('456', '789')]l = re.findall(r'\w+\s+\w+',s)
print(l)
#['abc def', 'ghi 123', '456 789']