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

更新于: 10-Jan-2020

326 次浏览

启动你的职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.