Monday, 25 December 2017

How to check multiple occurrences of 'is' in the input text | Java Regex | Regex in java


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

/**
 * Java regex example which uses the Matcher class to locate multiple
 * occurrences of the substring "is" inside a text: *
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {
        String inputCharSeq = "This is the text which is to be searched "
                + "for occurrences of the word 'is'.";

        String regex = "is";

        /*
         * Compiles the given regular expression into a pattern.
         */

        Pattern pattern = Pattern.compile(regex);
        /*
         * Returns:A new matcher for this pattern
         */

        Matcher matcher = pattern.matcher(inputCharSeq);

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

        while (matcher.find())
        {
            count++;
            System.out.println("found: " + count + " : "
                    + matcher.start() + " - " + matcher.end());
        }

    }

}

Output

found: 1 : 2 - 4
found: 2 : 5 - 7
found: 3 : 23 - 25
found: 4 : 70 - 72

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

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

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