如何使用 Java 中的正则表达式匹配 HTML 脚本中的粗体字段?

javaobject oriented programmingprogramming更新于 2025/2/9 8:12:17

正则表达式 "\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>一个 <b>示例>/b> HTML <b>脚本</b>。</p>";
      //用于匹配粗体标签内容的正则表达式
      String regex = "<b>(\S+)</b>";
      //创建一个 Pattern 对象
      //创建一个 Pattern 对象
      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>

相关文章


有用资源