Matcher appendTail() method in Java with Examples

JavaObject Oriented ProgrammingProgramming

The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.

The appendTail() method of this (Matcher) class accepts a StringBuffer object and append the characters of the input sequence to it.

Example

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AppendTail {
   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
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      StringBuffer sb = new StringBuffer();
      matcher.appendTail(sb);
      while (matcher.find()) {
         System.out.println(matcher.group(1));
      }
      System.out.println("Contents of the StringBuffer: \n"+ sb);
   }
}

Output

is
example
script
Contents of the StringBuffer:
<p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p>
raja
Published on 20-Nov-2019 06:40:45
Advertisements