一,代码格式
1、match
re.match(pattern, string[, flags])
从首字母开始开始匹配,string如果包含pattern子串,则匹配成功,返回Match对象,失败则返回None,若要完全匹配,pattern要以$结尾。
2、search
re.search(pattern, string[, flags])
若string中包含pattern子串,则返回Match对象,否则返回None,注意,如果string中存在多个pattern子串,只返回第一个。
3、findall
re.findall(pattern, string[, flags])
返回string中所有与pattern相匹配的全部字串,返回形式为数组。
4、finditer
re.finditer(pattern, string[, flags])
返回string中所有与pattern相匹配的全部字串,返回形式为迭代器。
- pattern : 正则中的模式字符串。
- string : 要被查找替换的原始字符串。
- flags : 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
补充:Pattern是java.util.regex(一个用正则表达式所订制的模式来对字符串进行匹配工作的类库包)中的一个类。一个Pattern是一个正则表达式经编译后的表现模式
二,例子详解
1.match 和search
import re s = '23432werwre2342werwrew' p = r'(\d*)([a-zA-Z]*)' m = re.match(p,s) || m=re.search(p,s) m.group() print(1,m.group()) print(2,m.group(0)) print(3,m.group(1)) print(4,m.group(2)) 结果都如下:
1 23432werwre
2 23432werwre
3 23432
4 werwre
我们发现,实际上search和match函数十分相似,但是怎么区别他们呢?
match
re.match()是从第一个字符开始一个一个字符去匹配 知道匹配一模一样的就返回匹配的结果 并且结束 。如果在从开头 ,往后匹配的过程中发现任何一个字符不匹配 结束匹配 返回None
search
re.search()方法扫描整个字符串,并返回第一个成功的匹配。如果匹配失败,则返回None。re.search()并不要求必须从字符串的开头进行匹配,也就是说,正则表达式可以是字符串的一部分。
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
print ("match --> matchObj.group() : ", matchObj.group())
else:
print ("No match!!")
matchObj = re.search( r'dogs', line, re.M|re.I)
if matchObj:
print ("search --> matchObj.group() : ", matchObj.group())
else:
print ("No match!!")
运行结果如下:
No match!! search --> matchObj.group() : dogs
三,项目运用
import re import requests url="http://www.dytt89.com/" resp=requests.get(url,verify=False)#去掉安全验证 resp.encoding='gb2312'#指定字符集 # print(resp.text) obj1 = re.compile(r'2021必看热片.*?<ul>(?P<ul>.*?)</ul>',re.S) obj2 = re.compile(r"<a href='(?P<href>.*?)'", re.S) obj3 = re.compile(r'◎片 名(?P<movie>.*?)<br />.*?<td ' r'style="WORD-WRAP: break-word" bgcolor="#fdfddf"><a href="(?P<download>.*?)">', re.S) result=obj1.finditer(resp.text) child_href_list = [] for it in result: ul=it.group("ul") # print(it.group("ul")) #提取子页面的链接 result1=obj2.finditer(ul) for itt in result1: newurl=url+itt.group("href").strip("/") child_href_list.append(newurl) # print(itt.group("href")) for href in child_href_list: child_resp = requests.get(href, verify=False) # 去掉安全验证 child_resp.encoding = 'gb2312' # 指定字符集 # print(child_resp.text) result3 = obj3.search(child_resp.text) print(result3.group("movie")) print(result3.group("download"))