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

จะจับคู่ฟิลด์ตัวหนาในสคริปต์ HTML โดยใช้นิพจน์ทั่วไปใน Java ได้อย่างไร


นิพจน์ทั่วไป "\\S" จับคู่อักขระที่ไม่ใช่ช่องว่างและนิพจน์ทั่วไปต่อไปนี้จะจับคู่อักขระที่ไม่ใช่ช่องว่างระหว่างแท็กตัวหนาอย่างน้อยหนึ่งตัว

"(\\S+)"

ดังนั้นเพื่อให้ตรงกับฟิลด์ตัวหนาในสคริปต์ HTML คุณต้อง -

  • รวบรวมนิพจน์ทั่วไปข้างต้นโดยใช้วิธีการคอมไพล์ ()

  • ดึงตัวจับคู่จากรูปแบบที่ได้รับโดยใช้วิธีการจับคู่ ()

  • พิมพ์ส่วนที่ตรงกันของสตริงอินพุตโดยใช้เมธอด 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>";
      //Regular expression to match contents of the bold tags
      String regex = "<b>(\\S+)</b>";
      //Creating a pattern object
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      //Creating an empty string buffer
      while (matcher.find()) {
         System.out.println(matcher.group());
      }
   }
}

ผลลัพธ์

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