Tuesday, 26 December 2017

How to use quote method of Pattern class | Regex in java


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

RegexDemo.java

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

public class RegexDemo
{

    private static String STRING_TO_BE_LITERALIZED = "dog$";
    private static String INPUT_CHAR_SEQ = "The dog$ says meow All dog$ say meow.";
    private static String REPLACE_STR = "cat";

    public static void main(String[] args)
    {
        /*
         * Returns:A literal string replacement
         */

        String regex = Pattern.quote(STRING_TO_BE_LITERALIZED);
        System.out.println("regex = "+regex);
        Pattern pattern = Pattern.compile(regex);

        // get a matcher object
        Matcher matcher = pattern.matcher(INPUT_CHAR_SEQ);
        INPUT_CHAR_SEQ = matcher.replaceAll(REPLACE_STR);
        System.out.println(INPUT_CHAR_SEQ);
    }

}

Output

regex = \Qdog$\E
The cat says meow All cat say meow.

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

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

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