Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Trích xuất thẻ HTML từ chuỗi bằng Regex trong Java

Dùng Pattern và Matcher để tìm thẻ HTML. Lưu ý: Regex KHÔNG phù hợp parse HTML phức tạp – hãy dùng Jsoup.

Ví dụ: Trích xuất nội dung thẻ <b>


import java.util.regex.*;

public class ExtractHtmlTagRegex {
    public static void main(String[] args) {
        String html = "Welcome to Tutorialspoint and Java programming";
        
        // Pattern: (nội dung) – group 1 là nội dung
        Pattern pattern = Pattern.compile("([^<]+)");
        Matcher matcher = pattern.matcher(html);
        
        System.out.println("Các thẻ  tìm thấy:");
        while (matcher.find()) {
            System.out.println("  - " + matcher.group(1)); // group 1 = nội dung trong ()
        }
    }
}

Kết quả


Các thẻ  tìm thấy:
  - Tutorialspoint
  - Java

Giải thích Pattern

  • <b> – khớp literal ""
  • ([^<]+) – group 1: 1+ ký tự KHÔNG phải '<' (tránh match cross-tag)
  • </b> – khớp literal ""

⚠️ Hạn chế nghiêm trọng của Regex cho HTML

Trường hợpRegex thất bại?
Tag lồng nhau: <div><b>x</b></div>Có thể sai
Attribute: <b class="bold">Sai (pattern không khớp)
Tag tự đóng: <br/>Sai
Comment/CDATASai
Malformed HTMLRất sai

Giải pháp đúng: Jsoup



import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

Document doc = Jsoup.parse(html);
Elements boldElements = doc.select("b"); // CSS selector
for (Element el : boldElements) {
    System.out.println(el.text());
}

Khi nào DÙNG regex?

  • HTML đơn giản, cấu trúc cố định, biết trước format
  • Trích xuất 1 lần, không cần robust
  • Không thể thêm dependency

Khuyến nghị mạnh mẽ: Dùng Jsoup cho mọi việc parse HTML production.