Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to search a text for regular expression using matches method in Java's String class


Program to demonstrate how to search a text for regular expression using matches method in Java's String class

package com.hubberspot.code;

public class MatchesDemo {

 public static void main(String[] args) {

  // Lets create a String. We have a long text assigned to it. 
  String text = "Welcome to Hubberspot 1.0 !";

  // String class has a method called as matches()
  // this method is been called over a String and takes
  // a parameter which is a regular expression. 
  // It returns a boolean value true or false whether or not 
  // string matches the given regular expression.
  // In the result variable below for the 1 it returns true 
  // because the regular expression passed is the exact match 
  // to the string
  boolean result = text.matches("Welcome to Hubberspot 1.0 !");
  System.out.println("1. : "+result);

  // for 2 result variable holds false because the regular 
  // expression passed is not the exact match to the string 
  result = text.matches("Welcome");
  System.out.println("2. : "+result);

  // for 3 result variable holds true because the regular
  // expression will test against both upper & lower case "W" and "H"
  // and will return true
  result = text.matches("[Ww]elcome to [Hh]ubberspot 1.0 !");
  System.out.println("3. : "+result);

  // for 4 result variable holds true because the regular
  // expression will test against a number checking whether 
  // it is in between 0 to 9
  result = text.matches("Welcome to Hubberspot [0-9].[0-9] !");
  System.out.println("4. : "+result);

  // for 5 result variable holds true because the regular
  // expression will test against alphanumeric combination
  // and will be used with any word holding .*
  result = text.matches("Welcome to .* [0-9].[0-9] !");
  System.out.println("5. : "+result);

 }
}



Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot