Tuesday 19 December 2017

How to use appendReplacement and appendTail methods of matcher class | Java Regex


Click here to watch in Youtube :
https://www.youtube.com/watch?v=e-SdxnqaEw0&list=UUhwKlOVR041tngjerWxVccw 

RegexDemo.java

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * The Matcher class provides appendReplacement and appendTail methods for text
 * replacement.
 *
 */

public class RegexDemo
{
    private static String REGEX = "aa";
    private static String INPUT = "aafooaafooaafooaa";
    private static String REPLACE = "-";

    public static void main(String[] args)
    {
        Pattern pattern = Pattern.compile(REGEX);
        Matcher matcher = pattern.matcher(INPUT);
       
        StringBuffer sb = new StringBuffer();
        while (matcher.find())
        {
            /*
             * Parameters:
             *
             * sb - The target string buffer
             * replacement - The replacement string
             *
             * Returns: This matcher
             *
             */

            matcher.appendReplacement(sb, REPLACE);
        }
        matcher.appendTail(sb);
        System.out.println(sb.toString());
    }

}

Output

-foo-foo-foo-

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/RegexDemo_append.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/RegexDemo_append

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/ef02c9011c18b0aa670526ba89cc11f493b9b854/BasicJava/RegexDemo_append/?at=master

See also:
  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment