Friday 5 January 2018

How to capturing the groups with back reference in Regex | Java Regex | Regex in java


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

RegexDemo.java

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

/**
 *
 * Capturing Groups
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {

        /*
         * Where there are two separate matches for the input, we can
         * have one match but propagating the same regex match to span
         * the entire length of the input using back referencing:
         */

        isMatch("(\\d\\d)\\1", "3434");
        isMatch("(\\d\\d)\\1", "3499");

        isMatch("(\\d\\d)\\1\\1", "343434");
        isMatch("(\\d\\d)\\1\\1", "343439");

    }

    private static void isMa tch(String regex, String inputText)
    {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(inputText);

        System.out.println("Regex = " + regex + " , " + "InputText = "
                + inputText + " is matching? = " + matcher.matches());
    }

}

Output

Regex = (\d\d)\1 , InputText = 3434 is matching? = true
Regex = (\d\d)\1 , InputText = 3499 is matching? = false
Regex = (\d\d)\1\1 , InputText = 343434 is matching? = true
Regex = (\d\d)\1\1 , InputText = 343439 is matching? = false

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

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

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