Python基础学习笔记DAY11
正则表达式(regular expression)
一种文本模式,描述在搜索文本时要匹配的一个或多个字符串
(ctrl+F显示)
- 典型场景:
(1)数据验证
(2)文本操作
(3)文本提取
(4)文本替换
(5)文本分割 - 语法:
- 字面值
(1)普通字符
(2)需转义 \;shift+6;shift+4; . ; | ; ? ; *; +; (); []; {} - 元字符
(1)正则表达式匹配规则:- 匹配单字,预定义元字符
(1). 除了\n外的所有字符
(2)\d,[0,9] 匹配数字
(3)\D, [shift+6 0-9] 匹配所有非数字
(4)\s 空白字符 \t\n\r\f\v
(5)\S 空白字符 [shift+6\t\n\r\f\v]
(6)\w; [a-zA-Z0-9_]匹配字母,数字,字符
(7)\W; [shift+6 a-zA-Z0-9_]非字母,数字,字符 - 批量备选
(1)| yes|no - 量词
(1)? 0或1次
(2)* 0或多次
(3) + 1或多次 - 特定
(1) {n,m} 范围次数
(2) {n} n次
(3) {n,} 至少n次
(4) {,m} 最多m次 - 贪婪与非贪婪
(1)贪婪(默认):尽量匹配最大范围结果
(2)非贪婪:尽量匹配最小的范围结果- 方法:量词后追加?
- 例:??/*?/+?
- 匹配边界
(1)shift+6 行首
(2)shift+4 行尾
(3)\b 单词边界
(4)\B 非单词边界
(5)\A 输入开头
(6)\Z 输入结尾
- 匹配单字,预定义元字符
- re模块
import re
text = 'Tom is 8 years old. Mike is 25 years old.'
pattern = re.compile('\d+') //反复重用时,编译提高运行效率
pattern.findall(text)
//输出结果为['8','25']
//方法2(不编译)
re.findall('\d+',text)
//输出结果为['8','25']
- RegexObject
模式对象,表现编译后的正则表达式(编译为字节码并缓存)
(1)编译:re.compile(‘模式’)
import re
s = "\\author:Tom"
pattern = re.compile('\\\\author')
pattern.findall(s)
//或
pattern = re.compile(r'\\author')
(2)RegexObject行为
- .findall()
(1)查找所有非重叠匹配项
(2)返回list - .match(string[,pos[,endpos]])
* import re
pattern = re.compile(r'<html>')
text = '<html><head></head><body></body></html>'
pattern.match(text)
//匹配成功
text = ' <html><head></head><body></body></html>'
pattern.match(text)
//匹配失败,返回空,因为match从开始位置来匹配
pattern.match(text)
//匹配成功,返回MatchObject
- MatchObject
匹配,仅从起始位置
(1)search(string[,pos[,endpos]]) 在任意位置搜索
import re
pattern = re.compile(r'<html>')
text = ' <html><head></head><body></body></html>'
pattern.search(text)
(2).finditer( ) 查找所有匹配项 返回包括MatchObject元素的迭代器
it = p1.finditer(text)
for m in it