Monday 25 December 2017

How to define multiple groups in a regular expression | Java Regex | Regex in java


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

RegexDemo.java

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

/**
 * Multiple Groups:
 * A regular expression can have multiple groups.
 *
 */

public class RegexDemo
{

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

        /*
         * This expression matches the text "John" followed by a
         * space, and then one or more characters.
         *
         * This expression contains a few characters with special
         * meanings in a regular expression. The . means
         * "any character". The + means "one or more times", and
         * relates to the . (any character, one or more times). The ?
         * means "match as small a number of characters as possible".
         */

        String regex = "(John) (.+?) ";

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

        while (matcher.find())
        {
            System.out.println("found: " + matcher.group(1) + " "
                    + matcher.group(2));
        }

    }

}

Output

found: John writes
found: John Doe
found: John Wayne

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

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/RegexDemo-multiple_group_john

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