Thursday, 21 December 2017

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


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

RegexDemo.java

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

/**
 *
 * Modifying/Substitution:
 *
 * Values in text can be replaced with new values, for example, you could
 * replace all instances of the word ‘PhoneNumber=’, followed by a number, with a
 * mask to hide the original text.
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {
        String inputCharSeq = "Peter PhoneNumber=9898988988. Juli PhoneNumber=7777766555";

        Pattern pattern = Pattern.compile("(PhoneNumber=)(\\d+)");
        Matcher matcher = pattern.matcher(inputCharSeq);

        StringBuffer sb = new StringBuffer();
        while (matcher.find())
        {
            System.out.println("Masking: " + matcher.group(2));
            matcher.appendReplacement(sb, matcher.group(1) + "***masked***");
        }
        matcher.appendTail(sb);
        System.out.println(sb);
    }

}

Output

Masking: 9898988988
Masking: 7777766555
Peter PhoneNumber=***masked***. Juli PhoneNumber=***masked***

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/576579fab6c376d5ecd7cb5b7402b7fd1a7c4ae3/BasicJava/RegexDemo_modify_phno/?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
  • 1 comment: