1. 程式人生 > >Python爬蟲-正則表達式基礎

Python爬蟲-正則表達式基礎

AR 替換 class find 字符串 存在 正則表達式基礎 TE hello

import re

#常規匹配
content = ‘Hello 1234567 World_This is a Regex Demo‘
#result = re.match(‘^Hello\s\d\d\d\s\d{4}\s\w{10}.*Demo$‘,content)
#print(result.group())
#print(result.span())

#泛匹配
#result = re.match("^Hello.*Demo$",content)
#print(result)


#目標匹配
#result = re.match(‘^Hello\s(\d+)\sWorld.*Demo$‘,content)
#print(result.group(1)) #貪婪(匹配盡可能多的字符) #result = re.match(‘^He.*(\d+).*Demo$‘,content) #非貪婪 #result = re.match(‘^He.*?(\d+).*Demo$‘,content) #print(result.group(1)) #匹配模式(存在換行符) #result = re.match(‘^He.*?(\d+).*Demo$‘,content,re.S) #轉義\ #總結:盡量使用泛匹配,使用括號得到匹配目標,盡量使用非貪婪模式,有換行re.S #re.search()掃描整個字符串並返回第一個匹配,match開頭需要一樣的
#re.findall(), 返回所有匹配的 #re.sub()替換 #re.compile()編譯正則表達式對象

Python爬蟲-正則表達式基礎