Tuesday, 26 December 2017

How to use Metacharacter dot | Java Regex | Java Regular Expressions | Regex in java


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

RegexDemo.java

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

/**
 * Meta Characters example
 */

public class RegexDemo
{

    public static void main(String[] args)
    {
        /*
         * Meta characters affect the way a pattern is matched, in a
         * way adding logic to the search pattern. The Java API
         * supports several metacharacters, the most straightforward
         * being the dot “." which matches any character:
         */

        calculateMatches(".", "foofoo");
        /*
         * Notice the dot after the foo in the regex. The matcher
         * matches every text that is preceded by foo since the last
         * dot part means any character after. So after finding the
         * first foo, the rest is seen as any character. That is why
         * there is only a single match.
         */

        calculateMatches("foo.", "foofoo");
    }

    private static void calculateMatches(String regex, String inputText)
    {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(inputText);
        int matches = 0;

        /*
         * The find method keeps advancing through the input text and
         * returns true for every match, so we can use it to find the
         * match count as well:
         */

        while (matcher.find())
        {
            ++matches;
        }
        System.out.println("Number of Matches = " + matches);
    }

}

Output

Number of Matches = 6
Number of Matches = 1

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

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

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