| 匹配左右任意一个表达式
#coding=utf-8
import re
ret = re.match("[1-9]?\d","8")
ret.group() # 8
ret = re.match("[1-9]?\d","78")
ret.group() # 78
# 不正确的情况
ret = re.match("[1-9]?\d","08")
ret.group() # 0
# 修正之后的
ret = re.match("[1-9]?\d$","08")
ret.group() # None
# 添加|
ret = re.match("[1-9]?\d$|100","8")
ret.group() # 8
ret = re.match("[1-9]?\d$|100","78")
ret.group() # 78
ret = re.match("[1-9]?\d$|100","08")
ret.group() # None
ret = re.match("[1-9]?\d$|100","100")
ret.group() # 100
(ab) 将括号中字符作为一个分组
#coding=utf-8
import re
ret = re.match("\w{4,20}@163\.com", "[email protected]")
ret.group()
ret = re.match("\w{4,20}@(163|126|qq)\.com", "[email protected]")
ret.group()
ret = re.match("\w{4,20}@(163|126|qq)\.com", "[email protected]")
ret.group()
ret = re.match("\w{4,20}@(163|126|qq)\.com", "[email protected]")
ret.group()
\num 引用分组num匹配到的字符串
#coding=utf-8
import re
# 能够完成对正确的字符串的匹配
ret = re.match("<[a-zA-Z]*>\w*</[a-zA-Z]*>", "<html>hh</html>")
ret.group()
# 如果遇到非正常的html格式字符串,匹配出错
ret = re.match("<[a-zA-Z]*>\w*</[a-zA-Z]*>", "<html>hh</htmlbalabala>")
ret.group()
# 正确的理解思路:如果在第一对<>中是什么,按理说在后面的那对<>中就应该是什么
# 通过引用分组中匹配到的数据即可,但是要注意是元字符串,即类似 r""这种格式
ret = re.match(r"<([a-zA-Z]*)>\w*</\1>", "<html>hh</html>")
ret.group()
# 因为2对<>中的数据不一致,所以没有匹配出来
ret = re.match(r"<([a-zA-Z]*)>\w*</\1>", "<html>hh</htmlbalabala>")
ret.group()
#coding=utf-8
import re
ret = re.match(r"<(\w*)><(\w*)>.*</\2></\1>", "<html><h1>www.itcast.cn</h1></html>")
ret.group()
ret = re.match(r"<(\w*)><(\w*)>.*</\2></\1>", "<html><h1>www.itcast.cn</h2></html>")
ret.group()
(?P) 分组起别名
(?P=name) 引用别名为name分组匹配到的字符串
#coding=utf-8
import re
ret = re.match(r"<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h1></html>")
ret.group()
ret = re.match(r"<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h2></html>")
ret.group()