開始使用免費開始

請把標籤關好!

同時,你也在處理另一個專案。公司正要開發一項新產品,能協助開發者自動檢查他們正在撰寫的程式碼。你需要寫一段小腳本,檢查每個開啟的 HTML 標籤是否都有正確的結尾標籤。

這裡有一個包含 HTML 標籤的字串範例:

<title>The Data Science Company</title>

你知道開頭的 HTML 標籤一定出現在字串的最前面,寫在 <> 之中。結尾標籤也在 <> 裡,但前面會有 /

你也記得可以用數字來參照擷取群組,例如 \4

清單 html_tags(包含 3 個含有 HTML 標籤的字串)以及 re 模組已經載入到你的工作階段。你可以用 print() 在 IPython Shell 中查看資料。

本練習屬於課程

Python 中的正規表示法

檢視課程

練習說明

  • 完成正則表達式以比對有正確關閉的 HTML 標籤。對清單 html_tags 中的每個字串尋找是否有符合的結果,並指派給 match_tag
  • 如果找到符合,印出儲存在 match_tag 中的第一個擷取群組。
  • 如果沒有符合,則完成另一個正則表達式,僅比對 HTML 標籤內的文字,並指派給 notmatch_tag
  • 印出由該正則表達式擷取並儲存在 notmatch_tag 的第一個群組。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

for string in html_tags:
    # Complete the regex and find if it matches a closed HTML tags
    match_tag =  re.match(____"<____>.*?", ____)
 
    if match_tag:
        # If it matches print the first group capture
        print("Your tag {} is closed".format(match_tag.____(____))) 
    else:
        # If it doesn't match capture only the tag 
        notmatch_tag = re.match(____"<____>", ____)
        # Print the first group capture
        print("Close your {} tag!".format(notmatch_tag.____(____)))
編輯並執行程式碼