如何使用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>";
//正则表达式以匹配粗体标签的内容
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>