一、结尾匹配
从字符串结尾开始匹配
返回匹配对象;如果找不到匹配,则为None
import reprint(re.match('飞兔小哥', '飞兔小哥教你零根底学编程'))print(re.match('学编程', '飞兔小哥教你零根底学编程'))
二、全匹配
匹配字符串是否和给定的字符截然不同
如果截然不同才返回匹配对象,如果找不到匹配,则为None
import reprint(re.fullmatch('飞兔小哥教你零根底学编程', '飞兔小哥教你零根底学编程'))print(re.fullmatch('飞兔小哥', '飞兔小哥教你零根底学编程'))
三、局部匹配
只有在字符串中找到字符存在即可
找到返回匹配对象,如果找不到匹配,则为None
import reprint(re.search('autofelix', '飞兔小哥教你零根底学编程'))print(re.search('飞兔小哥', '飞兔小哥教你零根底学编程'))
四、匹配替换
用正则表达式去匹配原始字符串,并把匹配到的内容替换
import re# 去掉电话号码中的-num = re.sub(r'\D', '', '188-1926-8053')print(num)# 18819268053
五、匹配替换返回数量
用正则表达式去匹配原始字符串,并把匹配到的内容替换
并且返回被替换掉的数量
import re# 去掉电话号码中的-num = re.subn(r'\D', '', '188-1926-8053')print(num)# (18819268053, 2)
六、宰割字符串
依照正则表达式的规定来宰割字符串,并返回列表
能够规定宰割的次数
import reprint(re.split('a*', 'hello world'))# ['', 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '']print(re.split('a*', 'hello world', 1))# ['', 'hello world']
七、匹配所有
在字符串中匹配所有合乎正则表达式的对象
并把这些对象通过列表list的模式返回
import repattern = re.compile(r'\W+')result1 = pattern.findall('hello world!') result2 = pattern.findall('hello world!', 0, 7)print(result1)# [' ', '!']print(result2)# [' ']
八、迭代器匹配
在字符串中匹配所有合乎正则表达式的对象
并把这些对象通过迭代器的模式返回
import repattern = re.compile(r'\W+') result = pattern.finditer('hello world!')for r in result: print(r)
九、编译对象
把正则表达式编译成Pattern对象
import repattern = re.compile(r'\W+')
十、修饰符
re.I:疏忽大小写
re.L:本地化辨认匹配
re.M:多行匹配
re.S:使.匹配包含换行在内的所有字符
re.U:依据unicode字符解析字符
re.X:给予灵便的格局以便了解
import recontent = "Cats are smarter than dogs"print(re.search(r'DOGS', content, re.M | re.I))
以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注Python技术大本营,获取更多技能与教程。