Friday 12 January 2018

How to use replacement methods of matcher class | Java Regex | Regex in java


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

RegexDemo1.java

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

/**
 *
 * Replacement Methods
 *
 */

public class RegexDemo1
{

    public static void main(String[] args)
    {
        Pattern pattern = Pattern.compile("dog");
        Matcher matcher = pattern
                .matcher("dogs are domestic animals, dogs are friendly");

        /*
         * Replacement methods are useful to replace text in an input
         * string. The common ones are replaceFirst and replaceAll.
         *
         * The replaceFirst and replaceAll methods replace the text
         * that matches a given regular expression. As their names
         * indicate, replaceFirst replaces the first occurrence, and
         * replaceAll replaces all occurrences.
         */

        String newStr = matcher.replaceFirst("cat");
        System.out.println(newStr);
    }

}

Output

cats are domestic animals, dogs are friendly

RegexDemo2.java

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

/**
 *
 * Replacement Methods
 *
 */

public class RegexDemo2
{

    public static void main(String[] args)
    {
        Pattern pattern = Pattern.compile("dog");
        Matcher matcher = pattern
                .matcher("dogs are domestic animals, dogs are friendly");

        /*
         * Replacement methods are useful to replace text in an input
         * string. The common ones are replaceFirst and replaceAll.
         *
         * The replaceFirst and replaceAll methods replace the text
         * that matches a given regular expression. As their names
         * indicate, replaceFirst replaces the first occurrence, and
         * replaceAll replaces all occurrences.
         */

        String newStr = matcher.replaceAll("cat");
        System.out.println(newStr);
    }

}

Output

cats are domestic animals, cats are friendly

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

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

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