1. 程式人生 > >python re模塊正則表達式

python re模塊正則表達式

request 一個 pre sea finditer all spa ref 返回

 1 re的工作是在python中執行正則表達式
 2 import re
 3 
 4 # find
 5 result = re.findall(\d+, baby的電話號是:185123456789)
 6 print(result)
 7 #
 8 it = re.finditer(\d+,baby的電話號是:185123456789)
 9 for i in it:
10     print(i.group()) # 分組
11 
12 # search 搜索, 查找
13 # 一旦匹配到結果. 直接返回, 如果匹配不到結果. 返回None
14 result = re.search(
\d,baby的電話號是:185123456789) 15 print(result) 16 print(result.group()) 17 # 18 # 19 # match 匹配, 從頭開始匹配. 相當於在你正則前面加了一個^ 20 result = re.match(\d+,185123456789baby的電話號是:) 21 print(result.group()) 22 23 # search和match的區別: search查找. 找到了結果就返回. match 從頭開始匹配 24 25 result = re.finditer(r姓名:(?P<name>.*?),愛好:(?P<hobby>.*?),
, 姓名:寶寶,愛好:女,性格開朗大方) 26 for i in result: 27 print(i.group(name), i.group(hobby))

簡單爬蟲

 1 from urllib.request import urlopen
 2 
 3 content = urlopen("https://www.dytt8.net/html/gndy/dyzz/20181219/57954.html").read().decode("gbk")
 4 # print(content)
 5 
 6 reg = r<div id="Zoom">.*?片  名(?P<name>.*?)<br />◎年  代(?P<years>.*?)<br />.*?◎上映日期(?P<date>.*?)<br />
+ 7 .*?◎主  演(?P<main>.*?)◎簡  介.*?<td style="WORD-WRAP: break-word" bgcolor="#fdfddf"><a href="(?P<download>.*?)"> 8 9 it = re.finditer(reg, content, re.S) # re.S 去掉.裏面的\n 10 11 for el in it: 12 print(el.group())

python re模塊正則表達式