English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Matcher useAnchoringBounds() method with example in Java

java.util.regex.Matcher class represents an engine for executing various matching operations. This class has no constructor, and it can be usedmatches()Method created by the java.util.regex.Pattern class/Get an object of this class.

Anchoring boundaries are used for area matching, such as ^ and $. By default, the matcher uses anchoring boundaries.

This classmethoduseAnchoringBounds()The method accepts a boolean value, if true is passed to this method, the current matcher will use anchoring bounds; if false is passed to this method, it will use non-fixed bounds.

example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Trail {
   public static void main( String args[] ) {
      //Read string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find numbers
      String regex = ".*\\d+.*";
      //Compile regular expression
      Pattern pattern = Pattern.compile(regex);
      //Print regular expression
      System.out.println("Compiled regular expression: ");+pattern.toString());
      //Retrieve matcher object
      Matcher matcher = pattern.matcher(input);
      matcher.useAnchoringBounds(false);
      boolean hasBounds = matcher.hasAnchoringBounds();
      if(hasBounds) {
         System.out.println("Current matcher uses anchoring bounds);
      } else {
         System.out.println("Current matcher uses non-anchoring bounds);
      }
   }
}

Output result

Enter input string
sample
Compiled regular expression: .*\d+.*
Current matcher uses non-anchoring bounds

example2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Sample {
   public static void main( String args[] ) {
      String regex = "^<foo>.*";
      String input = "<foo><bar>";//Hi</i></br> welcome to w3codebox";
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      matcher = matcher.useAnchoringBounds(false);
      if(matcher.matches()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
      System.out.println("Has anchoring bounds: ");+matcher.hasAnchoringBounds());
   }
}

Output result

Match found
Has anchoring bounds: false