1.re模块:Regular Expression
①、帮助信息
print('模块函数列表:',re.__all__)
print('模块版本:',re.__version__)
②、正则表达式修饰符
re.I 使匹配对大小写不敏感
re.L 做本地化识别(locale-aware)匹配
re.M 多行匹配,影响 ^ 和 $
re.S 使 . 匹配包括换行在内的所有字符
re.U 根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
re.X 该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。
['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'findall', 'finditer',
'compile', 'purge', 'template','escape', 'error',
'A', 'I', 'L', 'M', 'S', 'X', 'U',
'ASCII', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL','VERBOSE', 'UNICODE']
2.正则匹配练习
# 正则匹配
# 字符串正则匹配:regular expression
veryLongString = 'my name is Coder_LW'
# 寻找以'C'开头的字符串:区分大小写
result1 = re.findall(r'\bC[a-z,A-Z,_]*',veryLongString)
print(result1)
# re.match('正则表达式', string, flags=0),从字符串开头以'正则表达式'匹配
matchObject = re.match(r'a[a-z,A-Z,_]*',veryLongString)
matchObject2 = re.match(r'(.*)isis(.*?)',veryLongString,0)
# 返回匹配结果组,使用group()取值
if matchObject:
print(matchObject.group(0))
if matchObject2:
print('Match在起始位置:',matchObject2.span())
print(matchObject2.group())
print(matchObject2.group(1))
print(matchObject2.group(2))
# re.search(pattern, string, flags=0)
searchObject = re.search(r'isis(.*)',veryLongString,0)
if searchObject:
print('Search不在起始位置:',searchObject.span(),len(searchObject.groups()))
print(searchObject.group())
print(searchObject.group(1))
# re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;
# re.search则匹配整个字符串,直到找到一个匹配。
# re.sub(pattern, repl, string, count=0):检索+替换
subObject = re.sub(r'isis','is',veryLongString)
subObject2 = re.sub(r'i[is]{1,}s','is',veryLongString)
print('替换之后的字符串:',subObject)
print('替换之后的字符串2:',subObject2)
# 匹配邮箱或者电话号码
phone = '1234567¥#8910&这'
email = '1234567@163的萨达.com'
subPhoen = re.sub('\D','',phone)
subPhoen2 = re.sub('[^0-9]','',phone)
print('电话号码:',subPhoen)
print('电话号码2:',subPhoen2)
# 请求返回结果
response = zRequest().openUrl('https://www.baidu.com')
print('返回信息:',response.info())
# 截取主题区域
htmlStr = response.read().decode('utf-8')
htmlStr = re.sub('\s','',htmlStr)
# print(htmlStr)
# 编译正则表达式
# 笔记:
# .代表匹配任意一个字符,\.代表匹配.字符
# +意思是匹配+之前的一个字符1~n遍,*则是匹配*之前一个字符0~n次
# ?则设计到一个贪婪模式/懒惰模式:这里的?将+从贪婪模式更改到懒惰模式,贪婪模式会尽可能多的匹配字符
# 注意:在你使用"+","*"的时候,一定先想好到底是用贪婪型还是懒惰型,尤其是当你用到范围较大的项目上时,因为很有可能它就多匹配字符回来给你。
# {a,b}(代表a<=匹配次数<=b)
htmlPattern = re.compile(r'<[Hh][Tt][Mm][Ll]>.+?</[Hh][Tt][Mm][Ll]>')
bodyPattern = re.compile(r'<[Bb][Oo][Dd][Yy]>.+?</[Bb][Oo][Dd][Yy]>')
httpPattern = re.compile(r'https*:+?com')
htmlResults = re.findall(htmlPattern,htmlStr)
bodyResults = re.findall(bodyPattern,htmlStr)
httpResults = re.findall(httpPattern,htmlStr)
print('Html Ary : ',htmlResults)
print('Body Ary : ',bodyResults)
print('Http Ary : ',httpResults)
3.特殊字符类
①、 . 匹配除 "\n" 之外的任何单个字符。要匹配包括 '\n' 在内的任何字符,请使用象 '[.\n]' 的模式。
②、\d 匹配一个数字字符。等价于 [0-9]。
③、\D 匹配一个非数字字符。等价于 [^0-9]。
④、\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
⑤、\S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。
⑥、\w 匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'。
⑦、\W 匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'。
4.入门传送门