正则表达式:字符串匹配的模式,可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等
Python中使用正则表达式需导入模块,import re
>>> import re
>>> str=r'abcdefadabcd'
>>> s=r'abc'
>>> re.findall(s,str)
['abc', 'abc']
正则表达式规则:
- [ ]
常用来指定一个字符集,如 [abc]、[a-z]
元字符[ . ^ $ * + ? {} [] / | () ] 在字符集中不起作用,如
[abc$]
补集匹配不在字符集中的字符,如 [^5]
- ^
注:"[^5]"表示非5的字符,"^5"表示以5为行首的字符
- $
用于匹配行尾
- \
用于元字符的转义符,或代表特定模式:
\d 匹配任何十进制数,相当于类[0-9]
\D 匹配任何非数字字符,相当于类[^0-9]
\s 匹配任何空白字符,相当于类[\t\n\r\f\v]
\S 匹配任何非空白字符,相当于类[^\t\n\r\f\v]
\w 匹配任何字母数字字符,相当于类[a-zA-Z0-9]
\W 匹配任何非字母数字字符,相当于类[^a-zA-Z0-9]
- *
-- a[bcd]*d--"abcbd"
- +
- ?
- +?
- {m,n}
>>> r=r'^010-?\d{7}'
>>> re.findall(r,'010-4617333')
['010-4617333']
>>> re.findall(r,'0104617333')
['0104617333']
>>> re.findall(r,'010-4617333')
['010-4617333']
>>> re.findall(r,'0104617333')
['0104617333']
re模块的函数:
re.compile(r) 对字符串进行编译,速度更快
re.I 不限定大小写
tel=re.comfile(r,re.I)
match() 决定RE是否在字符串刚开始的位置匹配。
匹配成功,返回Match对象,失败则返回None,若要完全匹配,pattern要以$结尾。
>>> re.match(r'abc',r'ababcbcdf')
>>> re.match(r'abc',r'abcabcbcdf')
<_sre.SRE_Match object at 0x105c0aed0>
>>> re.match(r'abc',r'abcabcbcdf')
<_sre.SRE_Match object at 0x105c0aed0>
search() 扫描字符串,找到这个RE匹配的位置。
若string中包含pattern子串,则返回Match对象,否则返回None,如果string中存在多个pattern子串,
只返回第一个
。
>>> test=re.search(r'abc',r'abcabcbcdf')
>>> test.group() ## 返回匹配的字符串
'abc'
>>> test.start() ## 返回匹配开始的位置
0
>>> test.end() ## 返回匹配结束的位置
3
>>> test.span() ## 以元组形式,返回匹配开始和结束的位置
(0, 3)
>>> test.group() ## 返回匹配的字符串
'abc'
>>> test.start() ## 返回匹配开始的位置
0
>>> test.end() ## 返回匹配结束的位置
3
>>> test.span() ## 以元组形式,返回匹配开始和结束的位置
(0, 3)
sub() 替换字符串
>>> re.sub(r'r..t','python','rest rst riut rout')
'python rst python python'
'python rst python python'
split() 切割字符串
>>> test=r"abc aa;bb,cc | dd(xx).xxx 12.12' xxxx"
>>> re.split(r'[ ]*',test)
['abc', 'aa;bb,cc', '|', 'dd(xx).xxx', "12.12'", 'xxxx']
>>> re.split(r' *',test)
['abc', 'aa;bb,cc', '|', 'dd(xx).xxx', "12.12'", 'xxxx']
['abc', 'aa;bb,cc', '|', 'dd(xx).xxx', "12.12'", 'xxxx']
>>> re.split(r' *',test)
['abc', 'aa;bb,cc', '|', 'dd(xx).xxx', "12.12'", 'xxxx']
re.split 比 str.split 更适合非特定字符数量的规则
findall() 找到RE匹配的所有子串,并把它们作为一个列表返回
finditer() 找到RE匹配的所有子串,并把它们作为一个迭代器返回