Monday, 25 December 2017

What is the difference between lookingAt and matches methods of matcher class | Regex in java


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

RegexDemo.java

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

public class RegexDemo
{

    public static void main(String[] args)
    {
        String inputCharSeq = "Hello peter how are you?";

        String regex = "Hello peter";

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

        /*
         * The Matcher lookingAt() method works like the matches()
         * method with one major difference.
         *
         * The lookingAt() method only matches the regular expression
         * against the beginning of the text, whereas matches()
         * matches the regular expression against the whole text.
         *
         * In other words, if the regular expression matches the
         * beginning of a text but not the whole text, lookingAt()
         * will return true, whereas matches() will return false.
         */

        System.out.println("lookingAt = " + matcher.lookingAt());
        System.out.println("matches   = " + matcher.matches());
    }

}

Output

lookingAt = true
matches   = false

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

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

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