Tuesday 19 December 2017

How to use replaceAll and replaceFirst methods of matcher class | Regex in java


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

RegexDemo1.java

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

public class RegexDemo1
{
    private static String REGEX = "lion";
    private static String INPUT = "The lion says meow. All lions say meow.";
    private static String REPLACE = "cat";

    public static void main(String[] args)
    {
        Pattern pattern = Pattern.compile(REGEX);
        Matcher matcher = pattern.matcher(INPUT);
        /*
         * Parameters:
         *
         * replacement - The replacement string
         *
         * Returns:
         *
         * The string constructed by replacing each matching
         * subsequence by the replacement string, substituting
         * captured subsequences as needed
         */

        INPUT = matcher.replaceAll(REPLACE);
        System.out.println(INPUT);
    }

}

Output

The cat says meow. All cats say meow.

RegexDemo2.java

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

public class RegexDemo2
{
    private static String REGEX = "lion";
    private static String INPUT = "The lion says meow. All lions say meow.";
    private static String REPLACE = "cat";

    public static void main(String[] args)
    {
        Pattern pattern = Pattern.compile(REGEX);
        Matcher matcher = pattern.matcher(INPUT);
        /*
         * Parameters:
         *
         * replacement - The replacement string
         *
         * Returns:
         *
         * The string constructed by replacing the first matching
         * subsequence by the replacement string, substituting
         * captured subsequences as needed
         */

        INPUT = matcher.replaceFirst(REPLACE);
        System.out.println(INPUT);
    }
}

Output

The cat says meow. All lions say meow.

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/ef02c9011c18b0aa670526ba89cc11f493b9b854/BasicJava/RegexDemo_replace/?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