正则表达式是对字符串提取的一套规则,我们把这个规则用正则里面的特定语法表达出来,去匹配满足这个规则的字符串。正则表达式具有通用型,不仅python里面可以用,其他的语言也一样适用。
python中re模块提供了正则表达式的功能,常用的有四个方法(match、search、findall)都可以用于匹配字符串
一、正则表达式介绍
正则表达式是一个特殊的字符串序列,通常被用来检索、替换那些符合某个规范的文本
在python中使用re模块,可以写全部的正则表达式功能
二、match方法-匹配字符串
re.match()必须从字符串开头匹配!match方法尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。主要参数如下:
re.match(pattern, string) # pattern 匹配的正则表达式 # string 要匹配的字符串
import re a = re.match('test','testasdtest') print(a) #返回一个匹配对象re.Match类型对象 print(a.group()) #返回test,获取不到则报错 print(a.span()) #返回匹配结果的位置,左闭右开区间 print(re.match('test','atestasdtest')) #返回None
re.match()方法返回一个匹配的对象,而不是匹配的内容。如果需要返回内容则需要调用group()。通过调用span()可以获得匹配结果的位置。而如果从起始位置开始没有匹配成功,即便其他部分包含需要匹配的内容,re.match()也会返回None。
匹配规则
1、单字符匹配
以下字符,都匹配单个字符数据。且开头(从字符串0位置开始)没匹配到,即使字符串其他部分包含需要匹配的内容,.match也会返回none:
(1). 匹配任意一个字符,除了换行(后加一个re.S即可,忽略换行)
使用几个点号就代表几个字符:
import re a = re.match('..','testasdtest') print(a.group()) #输出te b = re.match('ab.','testasdtest') print(b) #返回none,因为表达式是以固定的ab开头然后跟上通配符. 所以必须要先匹配上ab才会往后进行匹配
#.匹配不了换行,报错 r1 = re.match(r'a.b','a\nb') ”“” 加了re.S之后,会忽略换行符,把字符串看作一个整体 a b “”“ r2 = re.match(r'a.b','a\nb',re.S)
(2)\d 匹配数字
一个\d代表一个数字。开头没匹配到,即使字符串其他部分包含需要匹配的内容,.match也会返回none
import re a = re.match('\d\d','23es12testasdtest') print(a) b = re.match('\d\d\d','23es12testasdtest') print(b) #要求匹配三个数字,匹配不到返回none c = re.match('\d','es12testasdtest') print(c) #起始位置没有匹配成功,一样返回none
(3)\D 匹配非数字
开头没匹配到,即使字符串其他部分包含需要匹配的内容,.match也会返回none
import re a = re.match('\D','23es12testasdtest') print(a) #开头为数字所以返回none b = re.match('\D\D','*es12testasdtest') print(b) #返回*e
(4)\s 匹配特殊字符,如空白,空格,tab等
import re print(re.match('\s',' 23es 12testasdtest')) #匹配空格 print(re.match('\s',' 23es 12testasdtest')) #匹配tab print(re.match('\s','\n23es 12testasdtest')) #匹配\r换行 print(re.match('\s','23es 12testasdtest')) #返回none
(5)\S 匹配非空白
import re print(re.match('\S',' 23es 12testasdtest')) #返回none print(re.match('\S','\r23es 12testasdtest')) #none print(re.match('\S','23es 12testasdtest'))
(6)\w 匹配单词、字符,如大小写字母,数字,_ 下划线
import re print(re.match('\w','23es 12testasdtest')) #返回none print(re.match('\w\w\w','aA_3es 12testasdtest')) #返回none print(re.match('\w\w\w','\n12testasdtest')) #返回none
(7)\W 匹配非单词字符
import re print(re.match('\W','23es 12testasdtest')) #返回none print(re.match('\W',' 23es 12testasdtest')) #匹配空格
(8)[ ] 匹配[ ]中列举的字符
只允许出现[ ]中列举的字符:
import re print(re.match('12[234]','232s12testasdtest')) #因为开头的12没匹配上,所以直接返回none print(re.match('12[234]','1232s12testasdtest')) #返回123
[^2345] 不匹配2345中的任意一个:
import re print(re.match('12[^234]','232s12testasdtest')) #因为开头的12没匹配上,所以直接返回none print(re.match('12[^234]','1232s12testasdtest')) #返回none print(re.match('12[^234]','1252s12testasdtest')) #返回125
[a-z3-5] 匹配a-z或者3-5中的字符:
import re print(re.match('12[1-3a-c]','1232b12testasdtest')) #123 print(re.match('12[1-3a-c]','12b2b12testasdtest')) #12b print(re.match('12[1-3a-c]','12s2b12testasdtest')) #返回none
2、表示数量
像上面写的那些都是匹配单个字符,如果我们要匹配多个字符的话,只能重复写匹配符。这样显然是不人性化的,所以我们还需要学习表达数量的字符
(1) * 出现0次或无数次
import re a = re.match('..','testasdtest') print(a.group()) #输出te a = re.match('.*','testasdtest') print(a.group()) #全部输出
import re print(re.match('a*','aatestasdtest')) #匹配跟随在字母a后面的所有a字符 print(re.match('\d*','23aatestasdtest')) #匹配前面为数字的字符 print(re.match('a\d*','ad23aatestasdtest')) #输出a, 因为*也可以代表0次
(2)+ 至少出现一次
import re #匹配前面为字母a的字符,且a至少有1一个 print(re.match('a+','aaatestasdtest')) print(re.match('a+','atestasdtest')) #a print(re.match('a+','caaatestasdtest')) #none
(3)? 最多出现1次,1次或则0次
import re print(re.match('a?','abatestasdtest')) #匹配a出现0次或者1次数 print(re.match('a?','batestasdtest')) #输出空,因为a可以为0次 print(re.match('a?','aaatestasdtest')) #a出现0次或者1次,输出1个a
(3){m}指定出现m次
import re #匹配t以及跟随在后面的三个ooo print(re.match('to{3}','toooooabatestasdtest')) print(re.match('to{3}','tooabatestasdtest')) #只有两个0,返回none
{m,n} 指定从m-n次的范围
import re print(re.match('to{3,4}','toooabatestasdtest')) #刚好有三个ooo,成功匹配 print(re.match('to{3,4}','tooabatestasdtest')) #只有两个o,返回none print(re.match('to{3,4}','toooooabatestasdtest')) #提取最多四个o
{m,}指定前一个元素最少出现m次
import re print(re.match('to{3,}','tooooabatestasdtest')) #匹配o最少出现3次,成功匹配tooo print(re.match('to{,1}','tooabatestasdtest')) #匹配o最多出现1次,返回none
3、匹配边界
(1)$ 匹配结尾字符
定义整个字符串必须以指定字符串结尾:
import re print(re.match('.*d$','2testaabcd')) #字符串必须以d结尾 print(re.match('.*c','2testaabcd')) #字符串不是以c结尾,返回none
(2)^ 匹配开头字符
定义整个字符串必须以指定字符开头:
import re print(re.match('^2','2stoooabatestas')) #规定必须以2开头,否则none print(re.match('^2s','2stoooabatestas')) #必须以2s开头
(3)\b 匹配一个单词的边界
\b:表示字母数字与非字母数字的边界,非字母数字与字母数字的边界。即下面ve的右边不能有字母和数字
import re #因为在python中\代表转义,所以前面加上r消除转义 print(re.match(r'.*ve\b','ve.2testaabcd')) print(re.match(r'.*ve\b','ve2testaabcd'))
(4)\B 匹配非单词边界
import re print(re.match(r'.*ve\B','2testaavebcdve')) #ve的右边需要有字母或者数字 print(re.match(r'.*ve\B','2testaave3bcdve'))
4、匹配分组
(1)| 匹配左右任意一个表达式
只要|两边任意一个表达式符合要求就行
import re print(re.match(r'\d[1-9]|\D[a-z]','2233')) #匹配|两边任意一个表达式 print(re.match(r'\d[1-9]|\D[a-z]','as'))
(2)(ab) 将括号中字符作为一个分组
()中的内容会作为一个元组字符装在元组中:
import re a = re.match(r'<h1>(.*)<h1>','<h1>你好啊<h1>') print(a.group()) #输出匹配的字符 ”“” 其中a.group(0)表示匹配全部的,a.group(1)表示分组匹配的第一个。。。 “”“ print(a.groups()) #会将()中的内容会作为一个元组字符装在元组中 print('`````````````') b = re.match(r'<h1>(.*)(<h1>)','<h1>你好啊<h1>') print(b.groups()) #有两括号就分为两个元组元素roup中默认是0,<h1>你好啊<h1> print(b.group(0)) #group(0)<h1>你好啊<h1> print(b.group(1)) #你好啊 print(b.group(2)) #h1
二、search 方法
和match差不多用法,从字符串中进行搜索
import re #从开头匹配 <re.Match object; span=(0, 2), match='12'> print(re.match(r'\d\d','123test123test')) #全部字符串中匹配查找 <re.Match object; span=(0, 2), match='12'> #只匹配第一个匹配到的 print(re.search(r'\d\d','123test123test')) #全部字符串中匹配查找 <re.Match object; span=(4, 6), match='12'> print(re.search(r'\d\d','test123test'))
三、findall 方法
从字面意思上就可以看到,findall是寻找所有能匹配到的字符,并以列表的方式返回
import re #<re.Match object; span=(3, 7), match='test'> print(re.search(r'test','123test123test')) #返回查找列表,['test', 'test'] print(re.findall(r'test','123test123test')) #以列表的方式返回
re.s:findall中另外一个属性re.S
在字符串a中,包含换行符\n,在这种情况下
- 如果不使用re.S参数,则只在每一行内进行匹配,如果一行没有,就换下一行重新开始。
- 而使用re.S参数以后,正则表达式会将这个字符串作为一个整体,在整体中进行匹配。
如下要寻找test.*123的数据,因为test和123在不同的行,如果没加re.s的话,他会在每一个进行匹配查找而不是将字符串作为一个整体进行查找:
import re a = """aaatestaa aaaa123""" print(re.findall(r'test.*123',a)) print(re.findall(r'test.*123',a,re.S)) ”“” []把每一行看作一个整体 ['testaa\naaaa123']把所有字符串看作一个整体 “”“
import re a = """aaatestaa123 testaaaa123""" print(re.findall(r'test.*123',a)) print(re.findall(r'test.*123',a,re.S)) ”“” ['testaa123', 'testaaaa123']每一行看作一个整体 ['testaa123\ntestaaaa123']把所有字符串看作一个整体 “”“
四、sub方法
查找字符串中所有相匹配的数据进行替换
re.sub(要替换的数据匹配规则,替换成什么,要替换的数据所在的数据)
import re print(re.sub('php','python','php是世界上最好的语言——php')) #输出 "python是世界上最好的语言——python"
五、split 方法
对字符串进行分割,并返回一个列表:
import re s = "itcase,java:php-php3;html" print(re.split(r",",s)) #以,号进行分割 print(re.split(r",|:|-|;",s)) #以,或者:或者-或者;进行分割 print(re.split(r",|:|-|%",s)) #找不到的分隔符就忽略 ”“” ['itcase', 'java:php-php3;html'] ['itcase', 'java', 'php', 'php3', 'html'] ['itcase', 'java', 'php', 'php3;html'] “”“
六、贪婪与非贪婪
python里的数量词默认是贪婪的,总是尝试尽可能的匹配更多的字符。python中使用?号关闭贪婪模式
import re print(re.match(r"aa\d+","aa2323")) #会尽可能多的去匹配\d print(re.match(r"aa\d+?","aa2323")) #尽可能少的去匹配\d ”“” <re.Match object; span=(0, 6), match='aa2323'> <re.Match object; span=(0, 3), match='aa2'> “”“
import re s = "this is a number 234-235-22-423" # 1.贪婪模式 #我们本想数字和字母拆解成两个分组 resule = re.match(r"(.+)(\d+-\d+-\d+-\d)",s) #('this is a number 23', '4-235-22-4') #但我们发现输出的结果中23的数字竟然被弄到前面去了 print(resule.groups()) #因为+它会尽可能多的进行匹配,\d,只需要一个4就能满足,所以前面就尽可能多的匹配 # 2.关闭贪婪模式 #在数量词后面加上 ?,进入非贪婪模式,尽可能少的进行匹配 result = re.match(r"(.+?)(\d+-\d+-\d+-\d)",s) print(result.groups()) #('this is a number ', '234-235-22-4')
七、案例-匹配ip地址
import re str = "http://10.1.1.1/index.html" try: s = re.search("\d*?\.\d*?\.\d*?\.\d*",str) print(s.group()) except: print("未能匹配出ip地址")