如何利用 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