1.re.match(pattern, string, flags=0)
是从字符串的句首进行匹配,如果句首匹配不到就返回none,group() 即为group(0),表示返回匹配到的整个字符串,group()可含有参数, 从1开始,返回一个对应的字符。groups()以元组的形式返回所有字符。下列情况的返回值为空。
import re
line = "Cats are smarter than dogs"
#.* 表示任意匹配除换行符(\n、\r)之外的任何单个或多个字符
matchObj = re.match(r'(.*) are (.*?) .*', line, re.M | re.I)
if matchObj:
print("matchObj.group() : ", matchObj.group())
print("matchObj.group(1) : ", matchObj.group(1))
print("matchObj.groups() : ", matchObj.groups())
结果如下:
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.groups() : ('Cats', 'smarter')
2.re.search(pattern, string, flags=0)
只返回匹配到的第一个数据,后面的不在匹配,也用group返回数据,
line = "Cats are 13214124smarter than 4324dogs"
matchObj = re.search(r'\d+', line, re.M | re.I)
if matchObj:
print("matchObj.group() : ", matchObj.group())
print("matchObj.groups() : ", matchObj.groups())
结果:
matchObj.group() : 13214124
matchObj.groups() : ()
3.re.compile(pattern[, flags])
用来生成一个正则表达式,供其他re的函数使用。
pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I) # re.I 表示忽略大小写
m = pattern.match('Hello World Wide Web')
print(m.span()) #span([group]) 方法返回 (start(group), end(group)),输出范围
4.findall(string[, pos[, endpos]])
找到字符串中所有符合正则表达式的子串,并返回一个列表,若无匹配项,则返回空列表
pattern = re.compile(r'\d+') # 查找数字
result1 = pattern.findall('runoob 123 google 456')
结果:['123', '456']
5.re.finditer(pattern, string, flags=0)
和findall()一样会匹配到所有的字串,但最终结果需要for循环获取,
it = re.finditer(r"\d+","12a32bc43jf3")
for match in it:
print (match.group())
6.re.split(pattern, string[, maxsplit=0, flags=0])
分割后返回列表,
maxsplit:分隔次数,maxsplit=1 分隔一次,默认为 0,不限制次数。
7.re.sub(pattern, repl, string, count=0, flags=0)
其中 repl : 替换的字符串
string:原始字符串
count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配