day16-re模块的使用

it2023-09-01  62

“”“author:Orange “””

re模块的使用

1.complie(正则表达式) - 编译正则表达式,返回正则对象

re_str = re.compile(r'[a-zA-Z0-9]\d{3}') 正则表达式对象.fullmatch(字符串) print(re_str.fullmatch('a123')) re.fullmatch(正则表达式,字符串) print(re.fullmatch(r'[a-zA-Z0-9]\d{3}', 'a123'))

2.匹配

fullmatch(正则, 字符串) - 让整个字符串和正则进行匹配, 匹配失败返回None,匹配成功返回匹配对象 match(正则, 字符串) - 让字符串的开头和正则进行匹配,匹配失败返回None, 匹配成功返回匹配对象

匹配对象

result = re.match(r'(\d{2})([a-z]{3})([A-Z]{2})', '54knmADSgngin') print(result) print(result.group())

1) 匹配到的子串

匹配对象.group() / 匹配对象.group(0) - 获取整个正则匹配到的子串 匹配对象.group(N) - 获取第N个分组匹配到的子串

2) 匹配范围 - 匹配到的子串在原字符串的下标范围

匹配对象.span() print(result.span()) print(result.span(2)) # (2, 5)

3.查找

search(正则, 字符串) - 在字符串中查到第一个满足正则要求的子串,如果找到了返回匹配对象,找不到返回None findall(正则, 字符串) - 在字符串中查找所有满足正则要求的子串, 返回值是列表, 列表中的 元素是字符串,如果找不着返回[]列表 re.finditer(正则, 字符串) - 获取字符串中所有满足正则的子串, 返回值是迭代器, 迭代器中的元是匹配对象

1) search()

2) findall()

有两个或者两个以上的分组: [(‘sd’, ‘236’), (‘sd’, ‘235’)] print(re.findall(r’([a-z]{2})(\d{3})’, ‘asd2365as56d52z3ad5—dsd235’))

3) finditer()

4)split()以及sub()

split(正则, 字符串) - 将字符串中满足正则的子串作为切割点 sub(正则, 字符串1, 字符串2) - 将字符串2中满足正则的子串全部替换成字符串1 print(re.split(r’\d+’, ‘asd2365as56d52z3ad5—dsd235’)) print(re.sub(r’\d+’, ‘+’, ‘asd2365as56d52z3ad5—dsd235’))

最新回复(0)