正则表达式
import re
result = re.match("\w{4,20}@163\.com$","hello@163.com")
if result:
print("match success!")
print("match content:", result.group())
else:
print("math fail!")
-
分组 |
import re result = re.match("^[0-9][0-9]$|^100$","77") #正则表达式匹配0~100之间的数字 |左右任意一个满足即可匹配 if result: print("match success!") print("match content:", result.group()) else: print("math fail!")
-
整体()
(abc)将括号中的字符作为一个整体进行匹配分组
分组从1开始计数,第一个小括号为组1
\w{4,20}@(163|126|qq|sina)\.com$ #匹配各种邮箱
提取区号和电话号码
import re result = re.match("(\d{3,4})-(\d{7,8})","023-12345678") if result: print("match success!") print("区号:", result.group(1)) #分组 print("电话号码:", result.group(2)) # 分组 else: print("math fail!")
-
引用分组 \
注意转义字符
import re result = re.match("<([a-zA-Z0-9]+)><([a-zA-Z0-9]+)>.*</\\2></\\1>","<div><h1>this is a string</h1></div>") #引用第一个分组,表示与第一组内容一致 \是转义字符 if result: print("match success!") print("match content:", result.group()) else: print("math fail!")
-
分组起别名(?P<name>)
-
分组引用别名(?P=name)
import re result = re.match("<(?P<name1>[a-zA-Z0-9]+)><(?P<name2>[a-zA-Z0-9]+)>.*</(?P=name2)></(?P=name1)>","<div><h1>this is a string</h1></div>") #引用第一个分组,表示与第一组内容一致 \是转义字符 if result: print("match success!") print("match content:", result.group()) else: print("math fail!")
-
re.findall()
返回满足正则条件的所有内容,是一个列表
import re result = re.findall("\d+","阅读次数999,转发次数888,评论次数777") #返回一个列表 if result: print("match success!") print("match content:", result) else: print("math fail!")
-
re.search()
找到第一个匹配即返回 类似find函数
-
re.match()
从字符串0号位置开始匹配,如果0号位置不满足即返回失败 即使从1号位可以匹配也是匹配失败
-
re.sub()
用一个新的字符串替换原来内容中满足正则表达式的内容
import re result = re.sub("\d+","1000","阅读次数999,转发次数888,评论次数777") # 把字符串中所有的正则替换为1000,返回替换后的内容 if result: print("match success!") print("match content:", result) else: print("math fail!")
-
re.split()
分割内容
import re result = re.split(":| ","info:hello@163.com tom jerry") if result: print("match success!") print("match content:", result) else: print("math fail!")
python默认是贪婪匹配,即总是尝试匹配尽可能多的字符
在+ * {} ?
后面加?
变成非贪婪,即只匹配一次就结束
获取电影天堂的电影
r.encoding = 'utf-8'
import re
import requests
def get_url(url):
try:
kv = {"user-agent":"Mozilla/5.0"}
r = requests.get(url,headers=kv)
r.raise_for_status()
r.encoding = 'gb2312'
demo = r.text
links = re.findall("ulink\">(.*?)</a>", demo)
for link in links:
print(link)
except Exception as e:
print(e)
if __name__ == '__main__':
head = "https://www.ygdy8.net/"
url = "https://www.ygdy8.net/html/gndy/dyzz/list_23_2.html"
get_url(url)