Basic Example of Regular Expression (Search for a single word)

Important Classes in Regular Expression

  • Pattern
    • A Pattern object represents a compiled version of regular expression.
    • We can create a Pattern Object by using compile() of Pattern Class
      public Static compile(String regularExpression)
      How to create a Pattern Object?
      Pattern p = Pattern.compile(“ab”);
  • Matcher
    • We can Use Matcher Object to Match the given Pattern in the target String.
    • We can Create Matcher Object by using matcher() of Pattern class.
      public Matcher matcher(String target)
      How to create a Matcher Object ?
      Matcher m = p.matcher(“ababbaba);
package demo.example1;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author Tyson
* Pattern String to find : ab
* Target String : ababbaba
* If available where it is available and how many times it is available
*/

public class Demo1 {
	public static void main(String[] args) {
		int count = 0;
		//Create a Pattern object of the String to be Searched
		//Pattern object represents the compiled version of regular expression string
		//Equivalent java object of Regular Expression word to be searched
		Pattern p = Pattern.compile("ab");
		/**
		 * Pattern is a factory method i.e If using class name we are calling a method
		 * and it returns object of the same class then we call it as a Static Factory method
		 */
		//Create a Matcher object of the String which is the Target string
		//in which pattern has to be searched
		Matcher m = p.matcher("ababbaba");
		//Find the matches in the Matcher object
		while(m.find()){
			//Print the start and end index of the match
			System.out.println(m.start()+"..."+m.end()+"..."+m.group());
			//Remember end() method returns value +1
			//group() method displays what got matched in the target
			count = count + 1;
		}
		System.out.println("Number of occurances : "+count);
	}
}
Output

Leave a Comment