Computer >> Computer tutorials >  >> Programming >> Java

Matcher useTransparentBounds() 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.

In regular expressions, the lookbehind and lookahead constructs are used to match a particular pattern that is preceding or, succeeding in some other pattern. For example, if you need to accept a string which accepts 5 to 12 characters the regular expression will be −

"\\A(?=\\w{6,10}\\z)";

By default, the boundaries of the matcher region are not transparent to the constructs look ahead, look behind and, boundary matching i.e. These constructs cannot match contents of the input text beyond the region boundaries −

Example 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class useTransparentBoundsExample {
   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

The useTransparentBounds() method of this class method accepts a boolean value and, if you pass true to this method the current matcher uses transparent bounds and if you pass false to this method it uses non-transparent bounds.

Example 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   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
      matcher = matcher.useTransparentBounds(true);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

Output

Enter 5 to 12 characters:
sampletext
Match found