Java中具有示例的Matcher requireEnd()方法
该java.util.regex.Matcher中的类代表一个引擎,进行各种匹配操作。此类没有构造函数,可以使用matches()类java.util.regex.Pattern的方法创建/获取此类的对象。
如果匹配,则此(Matcher)类的requireEnd()方法验证是否存在匹配结果为假的机会(如果有更多输入的话),如果是,则此方法返回true,否则返回false。
例如,如果您尝试使用正则表达式“you$”将输入字符串的最后一个单词与您匹配,并且如果您的第一个输入行是“helloyouare”,您可能会匹配,但是如果您接受更多句子新行的最后一个单词可能不是必需的单词(即“you”),从而使匹配结果为假。在这种情况下,该requiredEnd()方法返回true。
同样,如果您尝试匹配输入中的特定字符,请说#,并且如果您的第一个输入行是“Hello#你好吗”,您将有一个匹配项,更多的输入数据可能会更改匹配器的内容,但不会不要改变结果,这是真的。在这种情况下,该requiredEnd()方法返回false。
例子1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequiredEndExample {
public static void main( String args[] ) {
String regex = "you$";
//读取用户输入
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//实例化Pattern类
Pattern pattern = Pattern.compile(regex);
//实例化Matcher类
Matcher matcher = pattern.matcher(input);
//验证是否发生匹配
if(matcher.find()) {
System.out.println("Match found");
}
boolean result = matcher.requireEnd();
if(result) {
System.out.println("More input may turn the result of the match false");
} else{
System.out.println("The result of the match will be true, inspite of more data");
}
}
}输出结果
Enter input text: Hello how are you Match found More input may turn the result of the match false
例子2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequiredEndExample {
public static void main( String args[] ) {
String regex = "[#]";
//读取用户输入
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//实例化Pattern类
Pattern pattern = Pattern.compile(regex);
//实例化Matcher类
Matcher matcher = pattern.matcher(input);
//验证是否发生匹配
if(matcher.find()) {
System.out.println("Match found");
}
boolean result = matcher.requireEnd();
if(result) {
System.out.println("More input may turn the result of the match false");
} else{
System.out.println("The result of the match will be true, inspite of more data");
}
}
}输出结果
Enter input text: Hello# how# are you Match found The result of the match will be true, in spite of more data