Java 中的 Matcher hasAnchoringBounds() 方法附带示例
java.util.regex.Matcher 类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用 java.util.regex.Pattern 类的 matches() 方法创建/获取此类的一个对象。
限定边界用于匹配诸如 ^ 和 $ 之类的区域匹配。Matcher 默认使用限定边界,你可以使用 useAnchoringBounds() 方法从使用限定边界切换到不使用限定边界。
此 (Matcher) 类中的 hasAnchoringBounds() 方法验证当前 Matcher 是否使用了限定边界,如果使用了,则返回 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP