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

Método useAnchoringBounds () con ejemplo en Java

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

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

This classThe method'suseAnchoringBounds()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.

ejemplo1

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 the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Print the regular expression
      System.out.println("Compiled regular expression: ");+pattern.toString());
      //Search for 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");
      }
   }
}

Resultado de salida

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

ejemplo2

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("Coincidencia encontrada");
      } else {
         System.out.println("Coincidencia no encontrada");
      }
      System.out.println("Has anchoring bounds: ");+matcher.hasAnchoringBounds());
   }
}

Resultado de salida

Coincidencia encontrada
Has anchoring bounds: false