正则表达式是一种通用的字符串匹配模式,使用灵活功能强大.
一、Python正则表达式常见语法
二、常用的re函数
1.re.match(pattern, string, flags=0) 从字符串的起始位置匹配,如果起始位置匹配不成功的话,match()就返回none
参数:pattern: 描述匹配模式的正则字符串;string: 要匹配的文本;flag: 控制匹配模式的标志位.
判断string是否符合pattern, 返回match对象包含匹配的部分:
>>> import re
>>> text = 'This is Finley, welcome to join us.'
>>> m = re.match(r'\w*is\w*', text)
>>> m.group(0)
'This'
2.re.compile(pattern,flags=0)->regex #将正则表达式模式编译成正则表达式对象。
pattern #需要编译的正则表达式;flags #正则表达式使用的模式。re.S|re.M 开启多行模式和单行模式
常用模式有:re.I,re.M,re.S,re.X
为了提高效率,正则表达式可以被编译,这些编译后的结果被保存,下次使用同样的pattern的时候,就不需要再次编译。
编译后的对象同样可以使用match(),search()方法进行匹配。
单次匹配
re.match(pattern,string,flags=0)->match #匹配从字符串的开头匹配,返回match对象
regex.match(string[,pos[,endpos]])->match #regex对象match方法可以重设定开始位置和结束位置。返回match对象
pattern #正则表达式
string #需要匹配的字符串
flags #正则表达式使用的模式
常用模式有:re.I,re.M,re.S,re.X
pos #匹配字符串的开始位置,默认从0索引位置开始匹配
endpos #匹配字符串的结束位置(不包含结束位置),默认值为len(string)
示例:
import restr1 = """123456"""print(re.match("^\d*",str1,re.M))print(re.match("^\d*",str1))print(re.match("^[\d\n]*",str1,re.M))regex = re.compile("^\d*")print(regex.match(str1))
#注意regex可以重新指定字符串的开始位置,和结束位置(不包含结束位置)
print(regex.match(str1,0,2))
#注意:regex中开始位置和结束位置对^和$符号无影响,依然是指原字符串的开头和结尾
print(regex.match(str1,3)) #返回值为None,因为截开始的位置不是字符串的开头。所以无法匹配
3. re.search(pattern, string, flags=0) 扫描整个字符串并返回第一个成功的匹配
re.search寻找字符串内从任意位置开始的匹配, 而re.match只寻找从字符串的头部开始的匹配.
修改上例的可以发现两者的区别:
>>>text = 'Here is Finley, welcome to join us.'
>>> m = re.match(r'\w*is\w*', text)
>>> m is None
True
>>> m = re.search(r'\w*is\w*', text)
>>> m.group(0)
'is'
4.re.findall(pattern, string, flags=0) 找到RE匹配的所有字符串,并把他们作为一个列表返回
re.findall(pattern,string,flags=0)->list #对整个字符串从左至右匹配,返回所有匹配项的列表
regex.findall(string[,pos[,endpos]])->list #对整个字符串从左至右匹配,返回所有匹配项的列表
pattern #正则表达式
tring #需要匹配的字符
flags #模式
pos #匹配的起始位置
endpos #匹配的结束位置(不包含结束位置)
以列表的形式返回所有匹配的子串:
>>> import re
>>> text = 'This is Finley, welcome to join us.'
>>> m = re.findall(r'\w*is\w*', text)
>>> m
['This', 'is']
5.re.sub(pattern, repl, string, count=0, flags=0) 替换匹配到的字符串
将匹配的子串替换为repl字符串,;count参数指定替换个数, 默认为0表示全部替换.
import restr1 = "a23asldkf234xdd"print(re.sub("\d","你",str1))print(re.subn("\d","你",str1))print(re.sub("\d","你",str1,2))req = re.compile("\d")print(req.sub("爱",str1,3))print(req.subn("爱",str1))
6.re.split分割
re.split(pattern,string,maxsplit=0,flags=0)->list
regex.split(string,maxsplit=0)->list
import restr1 = "a1dslkd3ksdk245ks5jdf"print(re.split("\d",str1))print(re.split("\d",str1,2))print("----------")rep = re.compile("\d")print(rep.split(str1))print(rep.split(str1,1))print("---------------")print(re.split("k(s)",str1))
三、python中re模块提供了正则表达式相关操作
字符:
. 匹配除换行符以外的任意字符
\w 匹配字母或数字或下划线或汉字
\s 匹配任意的空白符
\d 匹配数字
\b 匹配单词的开始或结束
^ 匹配字符串的开始
$ 匹配字符串的结束
次数:
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次