负压风机厂家,双福语音浏览器,xt615拆机
原子是正则表达式中最基本的组成单位,每个正则表达式中至少要包含一个原子。
常见的原子类型:
#普通字符作为原子 import re string="iloveyou" pat="ve" res=re.search(pat,string) print(res) #非打印字符作为原子,如\n \t string='''hello world ''' pat="\n" res=re.search(pat,string) print(res) #通用字符作为原子 ''' \w 字母、数字、下划线 \w 除字母、数字、下划线 \d 十进制 \d 除十进制 \s 空白字符 \s 除空白字符 ''' string='''hello world 123''' pat="\d\d" res=re.search(pat,string) print(res) #原子表 #[xyz]:从中任意取一个原子 #[^xyz]:除xyz的任意一个字符 string="iloveyou" pat="i[^love]o" res=re.search(pat,string) print(res)
元字符是正则表达式中具有一些特殊含义的字符,比如重复n此前面的字符等。
可以在不改变正则表达式的情况下,通过模式修正符改变正则表达式的含义,从而实现一些匹配结果的调整等功能。
用法:
#模式修正符 string="python" pat="pyt" res=re.search(pat,string,re.i) print(res)
贪婪模式的核心点就是尽可能多的匹配,而懒惰模式是尽可能少的匹配。默认贪婪模式。
懒惰模式要加?
#贪婪模式与懒惰模式 string="poythonyhjskjsa" pat1="p.*y"#贪婪模式 pat2="p.*?y"#懒惰模式,精准 res1=re.search(pat1,string,re.i) res2=re.search(pat2,string,re.i) print(res1) print(res2)
匹配.com和.cn网址:
string="<a href='http://www.baidu.com'>百度首页</a>" pat="[a-za-z]+://[^\s]*[.com|.cn]" res=re.compile(pat).findall(string) print(res)
匹配电话号码:
string="afawda027-651315641s3dfs152sd" pat="\d{4}-\d{7}|\d{3}-\d{8}" res=re.compile(pat).findall(string) print(res)
import urllib.request data=urllib.request.urlopen("http://edu.csdn.net").read()
import urllib.request import re data=urllib.request.urlopen("https://edu.csdn.net/huiyicourse/detail/1041").read().decode("utf-8") pat="<p> 电话:(\d*?)</p>" res=re.compile(pat).findall(data) print(res[0])
import urllib.request import re data=urllib.request.urlopen("https://read.douban.com/provider/all").read().decode("utf-8") pat='<div class="name">(.*?)</div>' #加上圆括号后可以只显示括号里的内容 res=re.compile(pat).findall(data) with open("出版社","w") as fp: for i in range(len(res)): print(res[i]) fp.write(res[i]+'\n') fp.close()
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
python求numpy中array按列非零元素的平均值案例
网友评论