Syntax error Matcher useAnchoringBounds() method in Java with Examples

Matcher useAnchoringBounds() 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 anchoring bounds are used to match the region matches such as ^ and $. By default, a matcher uses anchoring bounds.

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

Example 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Trail {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find digits
      String regex = ".*\d+.*";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Printing the regular expression
      System.out.println("Compiled regular expression: "+pattern.toString());
      //Retrieving the 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

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

Example 2

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 Tutorialspoint";
      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

Match found
Has anchoring bounds: false
Updated on: 2019-11-20T07:32:57+05:30

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements