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