Python基础——贪婪模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34120459/article/details/87926676

一、贪婪模式简介

非贪婪模式(.*?) 即尽可能少的匹配字符:
.表示单个字符
* 表示{0,} 0到无穷多个字符
?表示{0,1} 0到1个字符
贪婪模式和非贪婪模式的对比
贪婪模式会尽可能多的匹配字符

import re
s = 'abcdecccccfg'
r1 = re.findall("ab.*c", s)  #贪婪模式
print(r1)   #['abcdeccccc']
r2 = re.findall("ab.*?c", s)  #非贪婪模式
print(r2)   #['abc']

二、贪婪模式的应用

import re
s = ""
with open("text.html", "r", encoding='utf-8')as f:
    s = f.read()
print(s)

s = re.findall('<dd id="contents">(.*?)</dd>', s, re.S)[0]    #想把列表变成字符串[0]
s = s.replace("<br />", "")
s = s.replace("&nbsp;", "")
print(s)

三、预定义字符组:[ ]

1、\d==[0-9]

import re
s = "<a href='asdf'>121423646</a>"
a = re.findall("(\d.*)", s)   #贪婪模式
b = re.findall("(\d.*\d)", s)   #贪婪模式
print(a)   #['121423646</a>']
print(b)   #['121423646']

2、\D===[^0-9] 非数字

a = re.findall("\D", s)
print(a)
['<', 'a', ' ', 'h', 'r', 'e', 'f', '=', "'", 'a', 's', 'd', 'f', "'", '>', '<', '/', 'a', '>']

3、\s 拿到空白符; \S拿到非空白符

import re
s = "fd\tpp\nre\t\ddd"
print(s)
a = re.findall("\s", s)
print(a)
b = re.findall("\S", s)
print(b)

4、\w:字母数字下划线汉字 \W

import re
s = '许嵩_v1986<a href="" >'
a = re.findall("\w", s)
print(a) #['许', '嵩', '_', 'v', '1', '9', '8', '6', 'a', 'h', 'r', 'e', 'f']
b = re.findall("\W", s)
print(b) #['<', ' ', '=', '"', '"', ' ', '>']

5、应用

import re
s = "[email protected]"
a = re.findall("^\w+@\w+\.com$", s)
print(a)  #['[email protected]']

三、正则常用函数

1、re.findall(): 将匹配的全部内容放入到一个列表中

2、re.match:从头开始匹配,只匹配字符串的开始

import re
s = "dogs are dog"
r1 = re.findall("d\w+", s)
r2 = re.match("d\w+", s)
r3 = re.match("(d)(\w+)", s)
print(r1)   #['dogs', 'dog']
print(r2)   #<re.Match object; span=(0, 4), match='dogs'>
print(r2.group())  #dogs   group()的作用是获取匹配到的值
print(r3.groups())  #('d', 'ogs')

3、re.search():全局匹配

import re
s = "Dogs are dog"
r = re.search("(d)(\w+)", s)
print(r.group())      #dog
print(r.groups())     #('d', 'og')

猜你喜欢

转载自blog.csdn.net/qq_34120459/article/details/87926676