Free Data Structures and Algorithms Course

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


Subscribe to all free courses

How to use Pattern and Matcher class for defining regular expressions in Java?

Program to demonstrate how to use Pattern and Matcher class for defining regular expressions in Java.

package com.hubberspot.code;

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

public class RegexDemo {

 public static void main(String[] args) {

  // Pattern class is used to store the representation
  // of regular expression. It is later used by Matcher 
  // class

  // Pattern class has static compile method 
  // which compiles the given regular expression
  // into a pattern and return a Pattern object to us
  Pattern pattern = Pattern.compile("xy"); 

  // Pattern has a matcher method that takes a sequence
  // of characters and Creates a matcher that will match the given input 
  // against the pattern created in previous step
  Matcher matcher = pattern.matcher("xyxxxyxabcaysbasxyyxxyyxshyxxy"); 

  // Matcher class has a find method that returns true or false
  // that whether there are any next sequence of matches
  while(matcher.find()) {

   // Matcher class has following methods :
   // 1. matcher.start() : returns the start index of the match found
   // 2. : returns the regular expression searched
   // 3. matcher.end() : returns the end index of match found
   System.out.print(matcher.start() + " " + + " " + matcher.end());




Output of the program :

© 2021 Learn Java by Examples Template by Hubberspot