天天看点

python正则表达式——分组的使用

在正则表达式里可以利用分组进行匹配,举例如下:

1.利用分组匹配邮箱地址:

>>> s = "[email protected]"
>>> p = r"(\w{4,20})@(163|qq|gmail|outlook)\.(com)"
>>> result = re.match(p, s)
>>> result.group()
'[email protected]'
>>> result.group()
'wangbo'
           

2.利用分组匹配html标签:分组1和2内容必须相互一致,照应于标记语言的规则。

>>> s = "<html><h1>what the fuck!</h1></html>"
>>> p = r"<(.+)><(.+)>(.+)</\2></\1>"
>>> re.match(p, s)
<_sre.SRE_Match object; span=(, ), match='<html><h1>what the fuck!</h1></html>'>
>>> re.match(p, s).group()
'what the fuck!'
           

3.利用取名字的方法进行匹配:类似于分组:

>>> s
'<html><h1>what the fuck!</h1></html>'
>>> p = r"<(?P<key1>.+)><(?P<key2>.+)>(.+)</(?P=key2)></(?P=key1)>"
#取名为key1、key2
>>> re.match(p, s)
<_sre.SRE_Match object; span=(, ), match='<html><h1>what the fuck!</h1></html>'>#匹配成功
>>> re.match(p, s).group()
'what the fuck!'#输出第三个分组