Wednesday, 15 November 2017

How to use compile and matcher methods of Pattern class | Java Regex


Click here to watch in Youtube :
https://www.youtube.com/watch?v=Wr_-tZYcSgk&list=UUhwKlOVR041tngjerWxVccw

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

public class RegexDemo1
{
    public static void main(String[] args)
    {
        /*
         * . represents single character
         *
         * Parameters:
         * 
         * regex - The expression to be compiled
         * 
         * Returns:
         * 
         * the given regular expression compiled into a pattern
         */
        Pattern pattern = Pattern.compile(".r");
        /*
         * Parameters: 
         * 
         * input - The character sequence to be matched
         * 
         * Returns: 
         * 
         * A new matcher for this pattern
         * 
         */
        Matcher matcher = pattern.matcher("br");
        /*
         * Returns:true if, and only if, the entire region sequence
         * matches this matcher's pattern
         */
        boolean result = matcher.matches();
        System.out.println(result);
    }

}
Output
true
RegexDemo2.java
import java.util.regex.Pattern;

public class RegexDemo2
{
    public static void main(String[] args)
    {
        boolean result=Pattern.compile(".r").matcher("ar").matches();  
        System.out.println(result);
    }

}
Output
true
RegexDemo3.java
import java.util.regex.Pattern;

/**
 * boolean java.util.regex.Pattern.matches(String regex, CharSequence
 * input)
 * 
 * Compiles the given regular expression and attempts to match the
 * given input against it
 */
public class RegexDemo3
{
    public static void main(String[] args)
    {
        /*
         * Parameters:
         * 
         * regex: The expression to be compiled
         * 
         * input: The character sequence to be matched
         * 
         * Returns:
         * 
         * whether or not the regular expression matches on
         * the input
         */
        boolean result = Pattern.matches(".r", "ar");
        System.out.println(result);
    }

}
Output
true

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/d5af812b33e9f57a10441740b1f80e2caf705d0c/BasicJava/RegexDemo_pattern_matcher/?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
  • Google+ Followers

    Google+ Badge