Monday, 8 January 2018

How to use boundary matchers[anywhere] in Regex | Java Regex | Regex in java


Click here to watch on Youtube : 
https://www.youtube.com/watch?v=9qEQ-c3ZSfg&list=UUhwKlOVR041tngjerWxVccw

RegexDemo.java

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

/**
 *
 * Boundary Matchers
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {

        /*
         * If we want a match only when the required text is found at
         * a word boundary, we use \\b regex at the beginning and end
         * of the regex:
         */

        calculateMatches("\\bdog\\b", "a dog is friendly");
        calculateMatches("\\bdog\\b", "dog is man's best friend,dog is good");
        calculateMatches("\\bdog\\b", "snoop dogg is a rapper");

        /*
         * Two-word characters appearing in a row does not mark a word
         * boundary, but we can make it pass by changing the end of
         * the regex to look for a non-word boundary:
         */

        calculateMatches("\\bdog\\B", "snoop dogg is a rapper");
    }

    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 = 1
Number of Matches = 2
Number of Matches = 0
Number of Matches = 1

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

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

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