re匹配
import re 1# # findall: 匹配字符串中所有的符合正则的内容 # lst = re.findall(r"\d+", "我的电话号是:10086, 我女朋友的电话是:10010") # print(lst) # 2# # finditer: 匹配字符串中所有的内容[返回的是迭代器], 从迭代器中拿到内容需要.group() # it = re.finditer(r"\d+", "我的电话号是:10086, 我女朋友的电话是:10010") # for i in it: # # print(i) #<re.Match object; span=(7, 12), match='10086'> # print(i.group()) 3# # search, 找到一个结果就返回, 返回的结果是match对象. 拿数据需要.group() # s = re.search(r"\d+", "我的电话号是:10086, 我女朋友的电话是:10010") # print(s.group()) 4# # match是从头开始匹配 # s = re.match(r"\d+", "10086, 我女朋友的电话是:10010") # print(s.group()) 5# # 预加载正则表达式 # obj = re.compile(r"\d+") # # ret = obj.finditer("我的电话号是:10086, 我女朋友的电话是:10010") # for it in ret: # print(it.group()) # # ret = obj.findall("呵呵哒, 我就不信你不换我1000000000") # print(ret)
6 #re.sub (替换)
import re
a ="https://video.pearvideo.com/mp4/adshort/20210708/1625804543078-15713872_adpkg-ad_hd.mp4"
c =re.sub(r"\d{13}", "你好我是替换的数据", a)
# download_url = re.sub(r"\d{13}", f"cont-{page}", download_url)
print(c) # https://video.pearvideo.com/mp4/adshort/20210708/你好我是替换的数据-15713872_adpkg-ad_hd.mp4
#示例:
s = """ <div class='jay'><span id='1'>郭麒麟</span></div> <div class='jj'><span id='2'>宋铁</span></div> <div class='jolin'><span id='3'>大聪明</span></div> <div class='sylar'><span id='4'>范思哲</span></div> <div class='tory'><span id='5'>胡说八道</span></div> """ # (?P<分组名字>正则) 可以单独从正则匹配的内容中进一步提取内容 obj = re.compile(r"<div class='.*?'><span id='(?P<id>\d+)'>(?P<wahaha>.*?)</span></div>", re.S) # re.S: 让.能匹配换行符 result = obj.finditer(s) for it in result: print(it.group("wahaha")) print(it.group("id"))
2 示例二:删除字符串中的符号
#删除字符串中的标点符号 -- re.sub的使用; str.maketrans import re import string data = "Stuning even for the non-gamer: This sound track was beautiful!\ It paints the senery in your mind so well I would recomend\ it even to people who hate vid. game music! I have played the game Chrono \ Cross but out of all of the games I have ever played it has the best music! \ It backs away from crude keyboarding and takes a fresher step with grate\ guitars and soulful orchestras.\ It would impress anyone who cares to listen!" # Methood 1 : Regex # Remove the special charaters from the read string. no_specials_string = re.sub('[!#?,.:";]', '', data) print(no_specials_string) # Methood 2 : translate() # Rake translator object translator = str.maketrans('', '', string.punctuation) data = data.translate(translator) print(data)
作者:华王
博客:https://www.cnblogs.com/huahuawang/