Matcher region(int start, int end) method in Java with Examples


The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.

The region() method of this (Matcher) class accepts two integer values representing positions in the input string and, sets a region of the current matcher.

Example 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionExample {
   public static void main(String[] args) {
      //Regular expression to accepts 6 to 10 characters
      String regex = "\A(?=\w{6,10}\z)";
      System.out.println("Enter 5 to 12 characters: ");
      String input = new Scanner(System.in).next();
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      //Setting region to the input string
      matcher.region(0, 4);
      //Switching to transparent bounds
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

Output

Enter 5 to 12 characters:
sampleText
Match not found

Example 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionExample {
   public static void main(String[] args) {
      String regex = "(.*)(\d+)(.*)";
      String input = "This is a sample Text, 1234, with numbers in between.";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      //Setting the region of the matcher
      matcher.region(0, 20);
      if(matcher.matches()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

Output

Match not found

Updated on: 20-Nov-2019

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements