How to match bold fields in a HTML script using a regular expression in Java?

The regular expression "\S" matches a non-whitespace character and the following regular expression matches one or more non space characters between the bold tags.


Therefore to match the bold fields in a HTML script you need to −

  • Compile the above regular expression using the compile() method.

  • Retrieve the matcher from the obtained pattern using the matcher() method.

  • Print the matched parts of the input string using the group() method.


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()) {