正則表達式筆記(re.search/re.match/re.split/re.compile/用法)


1. 正則表達式

https://www.cnblogs.com/douzujun/p/7446448.html

單詞邊界的用法(非常好用啊!!!)

 

比如,我只想替換 app 為 qq,不像替換掉 apple和application里的app

re.findall(r'\b\d{3}\b', '110 234 1234 355 67')
Out[53]: ['110', '234', '355']
re.findall(r'\b\d{3}\b', 'abd110 234 1234 355 67')
Out[55]: ['234', '355']

 

 

2. re.search

 

 

3. re.match()

 

>>> m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
>>> m <_sre.SRE_Match object; span=(0, 9), match='010-12345'> >>> m.group(0) '010-12345' >>> m.group(1) '010' >>> m.group(2) '12345'

4. re.findall

 

5. re.split()

>>> 'a b   c'.split(' ')
['a', 'b', '', '', 'c'] 嗯,無法識別連續的空格,用正則表達式試試: >>> re.split(r'\s+', 'a b c') ['a', 'b', 'c'] 無論多少個空格都可以正常分割。加入 , 試試: >>> re.split(r'[\s\,]+', 'a,b, c d') ['a', 'b', 'c', 'd'] 再加入;試試: >>> re.split(r'[\s\,\;]+', 'a,b;; c d') ['a', 'b', 'c', 'd']

6. re.finditer

7. re.sub

8. re.compile

如果一個正則表達式要重復使用幾千次,出於效率的考慮,我們可以預編譯該正則表達式,接下來重復使用時就不需要編譯這個步驟了,直接匹配:

>>> import re
# 編譯:
>>> re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
# 使用:
>>> re_telephone.match('010-12345').groups()
('010', '12345')
>>> re_telephone.match('010-8086').groups()
('010', '8086')

(1)用法1

(2)用法2

import re
string = '<h1 class="title">test_douzi</h1> <h1 class="title">test_douzi2</h1> <h1 class="title">test_douzi3</h1>'
pattern = '<h1 class="title">(.*?)</h1>'
s = re.compile(pattern).findall(string)

 

9. re.match對象

 

10. 貪婪匹配和最小匹配

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM