Java 的 Matcher hasTransparentBounds() 方法附带示例
java.util.regex.Matcher 类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用 java.util.regex.Pattern 类的 matches() 方法创建/获取此类的对象。
在正则表达式中,后向和前向构建用于匹配在其他模式中,在一些其他模式中先行或后续的特定模式。例如,如果您需要接受一个接受 5 到 12 个字符的字符串,则正则表达式为 −
"\A(?=\w{6,10}\z)";默认情况下,匹配器区域的边界对于构建前向、后向和边界匹配不透明,即这些构建不能匹配超出门区域边界的输入文本内容 −
此类的 hasTransparentBounds() 方法验证当前匹配器是否使用透明边界,如果是,则返回 true,否则,返回 false。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HasTransparentBounds {
public static void main(String[] args) {
//Regular expression to accepts 6 to 10 characters
String regex = "\A(?=\w{6,10}\z)";
System.out.println("Enter 5 to 12 characters: ");
String input = new Scanner(System.in).next();
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
//Setting region to the input string
matcher.region(0, 4);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
boolean bool = matcher.hasTransparentBounds();
//Switching to transparent bounds
if(bool) {
System.out.println("Current matcher uses transparent bounds");
} else {
System.out.println("Current matcher user non-transparent bound");
}
}
}输出
Enter 5 to 12 characters: sampletext Match not found Current matcher user non-transparent bound
示例 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HasTransparentBounds {
public static void main(String[] args) {
//Regular expression to accepts 6 to 10 characters
String regex = "\A(?=\w{6,10}\z)";
System.out.println("Enter 5 to 12 characters: ");
String input = new Scanner(System.in).next();
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
//Setting region to the input string
matcher.region(0, 4);
matcher.useTransparentBounds(true);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
boolean bool = matcher.hasTransparentBounds();
//Switching to transparent bounds
if(bool) {
System.out.println("Current matcher uses transparent bounds");
} else {
System.out.println("Current matcher user non-transparent bound");
}
}
}输出
Enter 5 to 12 characters: sampletext Match found Current matcher uses transparent bounds
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP