Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Java Regex: จับคู่ Bold Fields ใน HTML

Regex \\S จับคู่ non-whitespace character Regex ต่อไปจับคู่ 1+ non-space characters ระหว่างแท็ก bold:

"<b>(\\S+)</b>"

ขั้นตอน

  1. คอมไพล์ regex ด้วย Pattern.compile()
  2. สร้าง Matcher ด้วย matcher()
  3. พิมพ์ส่วนที่จับคู่ด้วย group()

ตัวอย่าง

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String[] args) {
        String str = "<p>This <b>is</b> an <b>example>/b> HTML <b>script</b>.</p>";
        String regex = "<b>(\\S+)</b>";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

ผลลัพธ์

<b>is</b>
<b>example</b>
<b>script</b>

อธิบาย

  • <b> - literal "<b>"
  • (\\S+) - capturing group: non-whitespace 1+ ตัว
  • </b> - literal "</b>"
  • matcher.group() = group 0 = ทั้งหมดรวมแท็ก
  • matcher.group(1) = แค่เนื้อหาในแท็ก (is, example, script)

ปัญหาของ Regex นี้

  • \\S+ หยุดที่ whitespace → ไม่จับคู่ "hello world" ภายใน <b> (จับแค่ "hello")
  • HTML จริงมักมี attribute: <b class="bold"> → ไม่จับคู่
  • Nested tags: <b>bold <i>italic</i></b> → จับคู่ผิด
  • Malformed HTML: missing closing tag → ผลลัพธ์ผิดพลาด

แนวทางที่ดีกว่า


// Non-greedy: จับคู่สั้นที่สุด รองรับ space ภายใน
String regex = "<b>(.*?)</b>";

// รองรับ attributes
String regex = "<b[^>]*>(.*?)</b>";

// ใช้ HTML Parser (แนะนำสำหรับ production)
/*
Document doc = Jsoup.parse(html);
Elements boldElements = doc.select("b");
for (Element el : boldElements) {
    System.out.println(el.text());
}
*/

สรุป

Regex เหมาะสำหรับ HTML เรียบง่าย/ควบคุมได้ สำหรับ HTML จริง ควรใช้ parser (Jsoup, Jericho, TagSoup)