Matcher useAnchoringBounds() method in Java with Examples
java.util.regex.Matcher类表示执行各种匹配操作的引擎。 该类没有构造函数,可以使用类java.util.regex.Pattern的matchs()方法创建/获取该类的对象。
锚定边界用于匹配区域匹配,例如^和$。 默认情况下,匹配器使用锚定边界。
此类方法的useAnchoringBounds()方法接受布尔值,如果将true传递给此方法,则当前匹配器将使用锚定边界;如果将false传递给此方法,则将使用非锚定边界。
例子1
<!-
现场演示
->
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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"); } } } |
输出量
1 2 3 4 | Enter input string sample Compiled regular expression: .*\d+.* Current matcher uses non-anchoring bounds |
例子2
<!-
现场演示
->
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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</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()); } } |
输出量
1 2 | Match found Has anchoring bounds: false |