Java 中的 Matcher useAnchoringBounds() 方法示例
javaobject oriented programmingprogramming更新于 2024/5/8 21:00:17
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[] ) {
//读取字符串值
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("Current matcher uses anchoring bounds");
} else {
System.out.println("Current matcher uses non-anchoring bounds");
}
}
}
输出
输入输入字符串 sample 编译的正则表达式:.*\d+.* 当前匹配器使用非锚定边界
示例 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("找到匹配");
} else {
System.out.println("未找到匹配");
}
System.out.println("有锚定边界:"+matcher.hasAnchoringBounds());
}
}
输出
找到匹配 有锚定边界:false
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/
打印
下一节:Java 中的 Matcher useTransparentBounds() 方法示例 ❯❮ 上一节:Java 中的 Matcher hasTransparentBounds() 方法示例

