Monday 18 December 2017

How to use String matcher in Java Regex | Java Regular Expressions | Regex in java


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

StringMatcher.java

public class StringMatcher
{
    /*
     * returns true if the string matches exactly "true"
     */

    public boolean isTrue(String s)
    {
        return s.matches("true");
    }

    /*
     * returns true if the string matches exactly "true" or "True"
     */

    public boolean isTrueVersion2(String s)
    {
        return s.matches("[tT]rue");
    }

    /*
     * returns true if the string matches exactly "true" or "True" or "yes" or
     * "Yes"
     */

    public boolean isTrueOrYes(String s)
    {
        return s.matches("[tT]rue|[yY]es");
    }

    /*
     * returns true if the string contains  "true"
     */

    public boolean containsTrue(String s)
    {
        return s.matches(".*true.*");
    }

}

RegexDemo.java

public class RegexDemo
{
    public static void main(String[] args)
    {
        StringMatcher stringMatcher = new StringMatcher();

        System.out.println(stringMatcher.isTrue("true")); // true
        System.out.println(stringMatcher.isTrue("True")); // false

        System.out.println("-----------------------------");

        System.out.println(stringMatcher.isTrueVersion2("true")); // true
        System.out.println(stringMatcher.isTrueVersion2("True")); // true
        System.out.println(stringMatcher.isTrueVersion2("True1")); // false

        System.out.println("-----------------------------");

        System.out.println(stringMatcher.isTrueOrYes("true")); // true
        System.out.println(stringMatcher.isTrueOrYes("Yes")); // true
        System.out.println(stringMatcher.isTrueOrYes("yes")); // true

        System.out.println("-----------------------------");

        System.out.println(stringMatcher.containsTrue("Hellotrue")); // true
        System.out.println(stringMatcher.containsTrue("WelcometrueWelcome")); // true
        System.out.println(stringMatcher.containsTrue("WelcometrWelcome")); // false

    }

}

Output

true
false
-----------------------------
true
true
false
-----------------------------
true
true
true
-----------------------------
true
true
false

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

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

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