如何利用 Java 中的正則表示式,匹配 HTML 指令碼中的粗體欄位?
正則表示式 "\S" 匹配非空白字元,下面的正則表示式匹配粗體標籤之間的至少一個非空白字元。
"(\S+)"
所以,要匹配 HTML 指令碼中的粗體欄位,你需 −
使用 compile() 方法編譯上述正則表示式。
使用 matcher() 方法從生成的模式中獲取匹配器。
使用 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>
廣告
資料結構
聯網
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP