Monday 25 December 2017

How to define single group in a regular expression | Java Regex | Regex in java


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

RegexDemo.java

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

/**
 *
 * This example searches the text for occurrences of the word John.
 * For each match found, group number 1 is extracted, which is what
 * matched the group marked with parentheses.
 *
 */

public class RegexDemo
{

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

        /*
         * Groups are marked with parentheses in the regular
         * expression.
         *
         * This regular expression matches the text John. The
         * parentheses are not part of the text that is matched. The
         * parentheses mark a group. When a match is found in a text,
         * you can get access to the part of the regular expression
         * inside the group.
         */

        String regex = "(John)";

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

        while (matcher.find())
        {
            /*
             * We access a group using the group(int groupNo) method.
             * A regular expression can have more than one group. Each
             * group is thus marked with a separate set of
             * parentheses. To get access to the text that matched the
             * subpart of the expression in a specific group, pass the
             * number of the group to the group(int groupNo) method.
             *
             * The group with number 0 is always the whole regular
             * expression. To get access to a group marked by
             * parentheses you should start with group numbers 1.
             */

            System.out.println("found: " + matcher.group(1) + " , start: "
                    + matcher.start() + ", end: " + matcher.end());
        }
    }

}

Output

found: John , start: 0, end: 4
found: John , start: 28, end: 32
found: John , start: 56, end: 60

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

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

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