正则表达式笔记(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'd{3}', '110 234 1234 355 67')
Out[53]: ['110', '234', '355']
re.findall(r'd{3}', '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. 贪婪匹配和最小匹配

  

原文地址:https://www.cnblogs.com/douzujun/p/12241804.html