Java 中 Matcher requireEnd() 方法及示例
java.util.regex.Matcher 类代表执行各种匹配操作的引擎。此类没有构造函数,您可以使用 java.util.regex.Pattern 类的 matches() 方法创建/获取此类的对象。
在匹配的情况下,此 (Matcher) 类的 requireEnd() 方法验证在更多输入的情况下,匹配结果是否有可能为假,如果是,则此方法返回 true,否则返回 false。
例如,如果您尝试使用正则表达式“you$”来匹配输入字符串的最后一个单词,并且您的第一行输入是“hello how are you”,您可能会得到匹配,但是,如果您接受更多句子,新行(s) 的最后一个单词可能不是所需的单词(即“you”),这将使您的匹配结果为假。在这种情况下,requiredEnd() 方法返回 true。
同样,如果您尝试匹配输入中特定字符(例如 #),并且您的第一行输入是“Hello # how are you”,您将得到匹配,并且更多输入数据可能会更改匹配器的内容,但不会更改结果(即为真)。在这种情况下,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$";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//Instantiating the Pattern class
Pattern pattern = Pattern.compile(regex);
//Instantiating the Matcher class
Matcher matcher = pattern.matcher(input);
//verifying whether a match occurred
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 = "[#]";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//Instantiating the Pattern class
Pattern pattern = Pattern.compile(regex);
//Instantiating the Matcher class
Matcher matcher = pattern.matcher(input);
//verifying whether a match occurred
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP