使用示例说明 Java 中 Matcher useAnchoringBounds() 方法
java.util.regex.Matcher 类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用 java.util.regex.Pattern 类的 matches() 方法创建/获取此类的对象。
锚定边界用于匹配区域匹配,例如 ^ 和 $。默认情况下,匹配器会使用锚定边界。
此类的 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[] ) {
//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");
}
}
}输出
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 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());
}
}输出
Match found Has anchoring bounds: false
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP