Java中具有示例的Matcher hasTransparentBounds()方法
java.util.regex.Matcher类表示执行各种匹配操作的引擎。该类没有构造函数,可以使用matches()类java.util.regex.Pattern的方法创建/获取该类的对象。
在正则表达式中,lookbehind和lookahead构造用于匹配在某些其他模式之前或之后的特定模式。例如,如果您需要接受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) {
//正则表达式可以接受6到10个字符
String regex = "\\A(?=\\w{6,10}\\z)";
System.out.println("Enter 5 to 12 characters: ");
String input = new Scanner(System.in).next();
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(input);
//将区域设置为输入字符串
matcher.region(0, 4);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
boolean bool = matcher.hasTransparentBounds();
//切换到透明范围
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) {
//正则表达式可以接受6到10个字符
String regex = "\\A(?=\\w{6,10}\\z)";
System.out.println("Enter 5 to 12 characters: ");
String input = new Scanner(System.in).next();
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(input);
//将区域设置为输入字符串
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();
//切换到透明范围
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