Tuesday 19 December 2017

How to count the number of times the word dog appears in the input string using Java Regex


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

RegexDemo.java

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

/**
 *
 * This example that counts the number of times the word "dog" appears in the
 * input string
 *
 */

public class RegexDemo
{
    private static final String REGEX = "\\bdog\\b";
    private static final String INPUT = "dog dog dog dogiee dog";

    public static void main(String[] args)
    {
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(INPUT); // get a matcher object
        int count = 0;

        /*
         * Returns:true if, and only if, a subsequence of the input sequence
         * matches this matcher's pattern
         */

        while (m.find())
        {
            count++;
            System.out.println("Match number " + count);
            /*
             * Returns the start index of the previous match.
             */

            System.out.println("start(): " + m.start());
            /*
             * Returns the offset after the last character matched.
             */

            System.out.println("end(): " + m.end());
            System.out.println("---------------------");
        }
    }

}

Output

Match number 1
start(): 0
end(): 3
---------------------
Match number 2
start(): 4
end(): 7
---------------------
Match number 3
start(): 8
end(): 11
---------------------
Match number 4
start(): 19
end(): 22
---------------------

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

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

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