1. 程式人生 > 其它 >正則表示式匹配html標籤

正則表示式匹配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) 表示使用變數,只不過把組當作一個變數,然後在使用這個變數
'''