正则表达式匹配html标签

匹配案例:

1、匹配: <h1>我喜欢python</h1>

import re

str = "<h1>我爱python</h1>"
result = re.match(r"<\w*>.*</\w*>",str)
print(result)

运行结果:
<re.Match object; span=(0, 17), match='<h1>我爱python</h1>'>

说明:html中的<>和/匹配时仍旧使用<>和/
\w可以匹配数字、字母、下划线、希腊字母、俄文字母等
*表示至少有0个
.匹配任意单字符,除了换行符\n
上述匹配有一个缺陷,<h1>我爱python</h2>这样的情况也是会匹配上的,所以要对标签进行分组
上面的匹配案例1就需要这样写:

import re

str = "<h1>我爱python</h1>"
result = re.match(r"<(\w*)>.*</\1>",str)
print(result)

'''
()表示组的意思
(\w*)表示有内容的一个组
\1表示第一组,和前面的\w*是一样的同一组
'''

2、匹配:<body><h1>我爱python</h1></body>

import re

str = "<body><h1>我爱python</h1></body>"
result = re.match(r"<(\w*)><(\w*)>.*</\2></\1>",str)
print(result)

运行结果:
<re.Match object; span=(0, 30), match='<body><h1>我爱python</h1></body>'>

说明:找到组的一一对应关系,从左往右数,组数从1开始然后按组别进行匹配
匹配案例2还有另外一种写法:

import re

str = "<body><h1>我爱python</h1></body>"
result = re.match(r"<(?P<n1>\w*)><(?P<n2>\w*)>.*</(?P=n2)></(?P=n1)>",str)
print(result)

'''
?P<n1>表示给组设置变量名,将其定义在组内。<>里的名字随意,如name1,name2都可以
(?P=n1) 表示使用变量,只不过把组当作一个变量,然后在使用这个变量
'''

猜你喜欢

转载自blog.csdn.net/weixin_51424938/article/details/113094615
今日推荐