Java 中的 Matcher hasAnchoringBounds() 方法及其示例
javaobject oriented programmingprogramming更新于 2024/5/8 19:56:17
java.util.regex.Matcher 类表示执行各种匹配操作的引擎。此类没有构造函数,您可以使用 java.util.regex.Pattern 类的 matches() 方法创建/获取此类的对象。
锚定边界用于匹配区域匹配,例如 ^ 和 $。默认情况下,匹配器使用锚定边界,您可以使用 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 = "这是一个示例文本,1234,中间有数字。"
+ "\n这是文本中的第二行"
+ "\n这是文本中的第三行";
//创建一个 Pattern 对象
Pattern pattern = Pattern.compile(regex);
//创建一个 Matcher 对象
Matcher matcher = pattern.matcher(input);
//验证锚定边界
boolean bool = matcher.hasAnchoringBounds();
//检查匹配
if(bool) {
System.out.println("当前匹配器使用锚定边界");
} else {
System.out.println("当前匹配器使用非锚定边界");
}
if(matcher.matches()) {
System.out.println("匹配找到");
} else {
System.out.println("匹配未找到");
}
}
}
输出
当前匹配器使用锚定边界 匹配未找到
示例 2
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("输入输入字符串");
String input = sc.nextLine();
//正则表达式查找数字
String regex = ".*\d+.*";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//打印正则表达式
System.out.println("编译后的正则表达式:"+pattern.toString());
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
matcher.useAnchoringBounds(false);
boolean hasBounds = matcher.hasAnchoringBounds();
if(hasBounds) {
System.out.println("当前匹配器使用锚定边界");
} else {
System.out.println("当前匹配器使用非锚定边界");
}
//验证是否匹配
if(matcher.matches()) {
System.out.println("给定字符串包含数字");
} else {
System.out.println("给定字符串不包含数字");
}
}
}
输出
输入输入字符串 hello sample 2 编译后的正则表达式:.*\d+.* 当前匹配器使用非锚定边界 给定字符串包含数字
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

