參考:
官方文檔https://docs.python.org/zh-cn/3.7/library/re.html
怎麼用https://docs.python.org/zh-cn/3.7/howto/regex.html#regex-howto
基本梳理和基本例子https://www.cnblogs.com/peng8098/p/python_basis_6.html
實際例子https://itbyc.com/Python/20353.html
經典例子https://blog.csdn.net/Flexin__/article/details/80023191
在線測試工具https://blog.csdn.net/z714405489/article/details/83217567
項目案例:羅攀,蔣仟《從零開始學Python網絡爬蟲》
https://www.jb51.net/article/170600.htm
正則表達式引擎in python https://www.cnblogs.com/secoding/p/11576864.html(代碼https://github.com/dejavudwh/Regex)
不錯的講解:http://www.regexlab.com/zh/regref.htm(注意未必與python的正則表達式規則相同)
學習過程:1. 大概的使用方法,2. 需要的積累查閱,3. 系統的總結沉澱
1. 大概的使用方法
- 常見規則
一般字符:., \, [...]
預定義字符集:\d, \D, \s, \S, \w, \W
數量詞:*, +, ?, {m}, {m,n}
邊界匹配:^, $, \A, \Z, \b
常見例子:re.S模式下, r‘(.*?)’表示以非貪婪模式匹配任何字符(如果不是re.S模式,則表示除了\n之外的任何字符),返回括號中的模式內容,具體使用見2.中非貪婪模式例子
注意:\w包含數字,字母以及下劃線,但是不包括-
例子:
result1 = re.findall(r'\w{2}', '_21-c34d-56_e78')
print(result1) #輸出:['_2', 'c3', '4d', '56', '_e', '78']
- 匹配方法
import re
results = re.findall(patt, string, flags)
例子:
result1 = re.findall(r'\d{2}', '21c34d56e78')
print(result1) #輸出:['21', '34', '56', '78']
- 替換方法
- 分裂方法
2. 需要的積累查閱
- 非貪婪模式 *?
例子:
result3 = re.findall(r'<p>(.*?)</p>', '<p>21c34d56e78</p>abc<p></p>7634', re.S)
print(result3) #輸出:['21c34d56e78', '']
3. 系統的總結沉澱