正则表达式的概述:
正则表达式使⽤单个字符串来描述、匹配 ⼀系列匹配某个句法规则的字符串。在很多⽂本编辑器⾥,正则表达式通常 被⽤来检索、替换那些匹配某个模式的⽂本。
最常用到的模块为re模块
re模块中用来正则匹配的方法一般为re.match和re.search,匹配成功后返回匹配对象,否则则为None,None不等价于空字符串 match的group的方法可以用来返回匹配部分。
import re
result=re.match('itcast','itcast.cn')
result.group()
运行得到的结果为itcast
re.match() 能够匹配出以xxx开头的字符串
re.search() 从全文中匹配出字符串
表示字符
. 匹配任意1个字符(除了\n)
[ ] 匹配[ ]中列举的字符
\d 匹配数字,即0-9
\D 匹配⾮数字,即不是数字
\s 匹配空⽩,即 空格,tab键
\S 匹配⾮空⽩
\w 匹配单词字符,即a-z、A-Z、0-9、_
\W 匹配⾮单词字符
Python中字符串前⾯加上 r表示原⽣字符串。与⼤多数编程语⾔相同,正则表达式⾥使⽤”\”作为转义字符 ,这就可能造成反斜杠困扰。假如你需要匹配⽂本中的字符”\”,那么使⽤编程语⾔表示的正则表达式⾥将需要4个反斜杠”\”:前两个和后两个分别⽤于在编程语⾔⾥转义 成反斜杠,转换成两个反斜杠后再在正则表达式⾥转义成⼀个反斜杠
匹配多个字符的相关格式
字符 功能
* 匹配前⼀个字符出现0次或者⽆限次,即可有可⽆
+ 匹配前⼀个字符出现1次或者⽆限次,即⾄少有1次
? 匹配前⼀个字符出现1次或者0次,即要么有1次,要么没有
{m} 匹配前⼀个字符出现m次
{m,} 匹配前⼀个字符⾄少出现m次
{m,n} 匹配前⼀个字符出现从m到n次
示例1:$
需求:匹配163.com的邮箱地址
import re
# 正确的地址 ret = re.match("[\w]{4,20}@163\.com", "xiaoWang@163.com") ret.group()
# 不正确的地址 ret = re.match("[\w]{4,20}@163\.com", "xiaoWang@163.comheihei" ) ret.group()
# 通过$来确定末尾 ret = re.match("[\w]{4,20}@163\.com$", "xiaoWang@163.comheihe i") ret.group()
import re
# re_obj = re.match('[^asdhH]+?','woknhlj')
# re_obj = re.match('[a-z A-Z 0-9 ]{5}','woknhlj')
re_obj = re.match('^4.*[369]$','235434FDDHTFJ9')
re_obj = re.search('4.*[369]$','235434FDDHTFJ9')
print (re_obj.group())
# mylist = ['apple','banana','pen','orange']
# mylist = ['aaa@163.com','bbb@126.com','ccc@qq.com']
# for i in mylist:
# match_obj = re.match('\w{3,15}@(163|126)\.com$',i)
# if match_obj:
# print(match_obj.group())
# print(match_obj.group(1))
# else:
# print('没有')
# # try:
# print(re_obj.group())
# except Exception as e:
# print(e)
匹配网页
import re
content = '<html>hello world</html>'
# obj = re.match('<[a-zA-Z0-9]+>(.*)</[a-zA-Z0-9]+>',content)
# if obj:
# print(obj.group(1))
# else:
# print('0')
# obj = re.match('<([a-zA-Z0-9]+)>(.*)</\\1>',content)
# if obj:
# print(obj.group(2))
# else:
# print('0')
# content1 = '<html><h1>hello world</h1></html>'
# obj = re.match('<([a-zA-Z0-9]+)><([a-zA-Z0-9]+)>(.*)</\\2></\\1>',content1)
# if obj:
# print(obj.group(3))
# else:
# print('0')
content1 = '<html><h1>hello world</h1></html>'
obj = re.match('<(?P<name1>[a-zA-Z0-9]+)><(?P<name2>[a-zA-Z0-9]+)>(.*)</(?P=name2)></(?P=name1)>',content1)
if obj:
print(obj.group(3))
else:
print('0')
re.sub 替换。将匹配到的数据进行替换
#coding=utf-8 import re
ret = re.sub(r"\d+", '998', "python = 997") print ret