ใช้แพ็กเกจ java.util.regex มีคลาสหลัก 2 คลาส:
- Pattern - compiled regex
- Matcher - engine สำหรับ match operation
เมธอดสำคัญของ Matcher
find()- หา match ถัดไป คืน booleangroup()- คืนค่าทั้งหมดที่ matchgroup(int n)- คืนค่า capturing group ที่ n (group 0 = ทั้งหมด)
ตัวอย่าง: ดึงเนื้อหาใน <b>...</b>
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractHtmlTag {
public static void main(String[] args) {
String str = "Welcome to Tutorialspoint";
// Pattern: (capture group)
Pattern pattern = Pattern.compile("(\\S+)");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String content = matcher.group(1); // group 1 = (\S+)
System.out.println("Extracted: " + content);
}
}
}
ผลลัพธ์
Extracted: Tutorialspoint
Regex Patterns สำหรับ HTML Tags
| Pattern | คำอธิบาย | ตัวอย่าง Match |
|---|---|---|
<b>(\\S+)</b> | Tag b, เนื้อหาไม่มี space | Hello |
<b>([^<]+)</b> | Tag b, เนื้อหาไม่มี < (รองรับ space) | Hello World |
<(\\w+)>([^<]+)</\\1> | Tag ใดๆ + เนื้อหา (backreference \\1) | Italic, Content |
<([^>]+)>([^<]*)</\\1> | Tag ที่มี attribute ได้ | Text |
ตัวอย่าง: Extract ทุก Tag แบบ Generic
String html = "Title
Paragraph bold
";
Pattern pattern = Pattern.compile("<(\\w+)[^>]*>([^<]*)\\1>");
Matcher matcher = pattern.matcher(html);
while (matcher.find()) {
String tagName = matcher.group(1);
String content = matcher.group(2);
System.out.println(tagName + ": " + content);
}
ผลลัพธ์
h1: Title
p: Paragraph
b: bold
⚠️ ข้อจำกัดสำคัญ: Regex ไม่ควร Parse HTML
HTML เป็น nested structure (context-free grammar) Regex เป็น regular language (regular grammar) Regex ไม่สามารถ parse HTML ที่ซ้อนกันได้ถูกต้อง
// นี้จะ fail หรือผิดพลาด
String nested = "inner";
// Regex จะ match ผิด: inner แทนที่จะเป็น outer div
แนะนำ: ใช้ HTML Parser (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");
for (Element el : boldElements) {
System.out.println(el.text());
}
// หรือ select ทุก element
Elements all = doc.select("*");
for (Element el : all) {
System.out.println(el.tagName() + ": " + el.text());
}
สรุป
- Regex: ใช้ได้เฉพาะ HTML แบบ flat, simple, known structure
- Jsoup: ใช้สำหรับ HTML จริง, nested, malformed, extraction ซับซ้อน
- Production code: อย่าใช้ Regex parse HTML - ใช้ Jsoup หรือ HTML parser อื่น
-
-
-
-