Monday 25 December 2017

How to replace the values in the text with new values using replace methods | Regex in java


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

RegexDemo.java

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

/**
 *
 * replaceAll() and replaceFirst():
 *
 * The Matcher replaceAll() and replaceFirst() methods can be used to
 * replace parts of the string the Matcher is searching through.
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {
        String text = "John peter about this, and John Doe writes about that,"
                + " and John Wayne writes about everything.";

        String regex = "(John)";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        /*
         * The replaceAll() method replaces all matches of the regular
         * expression.
         */

        String replaceAll = matcher.replaceAll("Steve");
        System.out.println("replaceAll   = " + replaceAll);

        /*
         * The replaceFirst() only replaces the first match.
         */

        String replaceFirst = matcher.replaceFirst("Steve");
        System.out.println("replaceFirst = " + replaceFirst);
    }

}

Output

replaceAll   = Steve peter about this, and Steve Doe writes about that, and Steve Wayne writes about everything.
replaceFirst = Steve peter about this, and John Doe writes about that, and John Wayne writes about everything.

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

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

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