Java中具有示例的Matcher hasAnchoringBounds()方法
java.util.regex.Matcher类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用类java.util.regex.Pattern的matchs()方法创建/获取此类的对象。
锚定边界用于匹配区域匹配,例如^和$。默认情况下,匹配器使用锚定范围,您可以使用useAnchoringBounds()方法从使用锚定范围切换到非锚定范围。
此(Matcher)类的hasAnchoringBounds()方法验证当前匹配器是否使用锚定边界(如果是),否则返回true,否则返回false。
例子1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class HasAnchoringBoundsExample { public static void main(String[] args) { String regex = "(.*)(\\d+)(.*)"; String input = "This is a sample Text, 1234, with numbers in between. " + "\n This is the second line in the text " + "\n This is third line in the text"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(input); //Verifying for anchoring bounds boolean bool = matcher.hasAnchoringBounds(); //checking for the match if(bool) { System.out.println("Current matcher uses anchoring bounds"); } else { System.out.println("Current matcher uses non-anchoring bounds"); } if(matcher.matches()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } } }
输出结果
Current matcher uses anchoring bounds Match not found
例子2
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"); } //verifying whether match occurred if(matcher.matches()) { System.out.println("Given String contains digits"); } else { System.out.println("Given String does not contain digits"); } } }
输出结果
Enter input string hello sample 2 Compiled regular expression: .*\d+.* Current matcher uses non-anchoring bounds Given String contains digits