Java中具有示例的Matcher useAnchoringBounds()方法
java.util.regex.Matcher类表示执行各种匹配操作的引擎。该类没有构造函数,可以使用matches()
类java.util.regex.Pattern的方法创建/获取该类的对象。
锚定边界用于匹配区域匹配,例如^和$。默认情况下,匹配器使用锚定边界。
此类方法的useAnchoringBounds()方法接受一个布尔值,如果将true传递给此方法,则当前匹配器将使用定位范围;如果将false传递给此方法,则将使用非固定范围。
例子1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Trail { public static void main( String args[] ) { //读取字符串值 Scanner sc = new Scanner(System.in); System.out.println("Enter input string"); String input = sc.nextLine(); //查找数字的正则表达式 String regex = ".*\\d+.*"; //编译正则表达式 Pattern pattern = Pattern.compile(regex); //打印正则表达式 System.out.println("Compiled regular expression: "+pattern.toString()); //检索匹配器对象 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"); } } }
输出结果
Enter input string sample Compiled regular expression: .*\d+.* Current matcher uses non-anchoring bounds
例子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 Nhooo"; 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()); } }
输出结果
Match found Has anchoring bounds: false