Thursday 21 December 2017

How to extract specific values from the text | Java Regex | Java Regular Expressions | Regex in java


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

RegexDemo.java

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

/**
 *
 * Extracting/Capturing:
 *
 * Specific values can be selected out of a large complex body of text. These
 * values can be used in the application.
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {
        String inputCharSeq = "I have a cat, but I like my dog better.";

        /*
         * () - group everything within the parenthesis as group 1
         *
         * mouse - match the text ‘mouse’
         *
         * | - alternation: match any one of the sections of this group
         *
         * cat - match the text ‘cat’
         */


        Pattern pattern = Pattern.compile("(mouse|cat|dog|wolf)");
        Matcher matcher = pattern.matcher(inputCharSeq);

        List<String> animalList = new ArrayList<String>();
        while (matcher.find())
        {
            System.out.println("Found a " + matcher.group() + ".");
            animalList.add(matcher.group());
        }

        System.out.println("animalList = " + animalList);
    }

}

Output

Found a cat.
Found a dog.
animalList = [cat, dog]

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

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

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