當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Scanner match()用法及代碼示例


java.util.Scanner類的match()方法返回此掃描程序執行的最後一次掃描操作的匹配結果。

用法:

public MatchResult match()

返回值:此函數返回上一次匹配操作的匹配結果。


異常:如果未執行任何匹配,或者上一次匹配失敗,則該函數將拋出IllegalStateException。

以下示例程序旨在說明上述函數:

示例1:

// Java program to illustrate the 
// match() method of Scanner class in Java 
// without parameter 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        String s = "GFG Geeks!"; 
  
        // create a new scanner 
        // with the specified String Object 
        Scanner scanner = new Scanner(s); 
  
        // check if next token is "GFG" 
        System.out.println("" + scanner.hasNext("GFG")); 
  
        // find the last match and print it 
        System.out.println("" + scanner.match()); 
  
        // print the line 
        System.out.println("" + scanner.nextLine()); 
  
        // close the scanner 
        scanner.close(); 
    } 
}
輸出:
true
java.util.regex.Matcher[pattern=GFG region=0, 10 lastmatch=GFG]
GFG Geeks!

示例2:演示IllegalStateException

// Java program to illustrate the 
// match() method of Scanner class in Java 
// without parameter 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            String s = "GFG Geeks!"; 
  
            // create a new scanner 
            // with the specified String Object 
            Scanner scanner = new Scanner(s); 
  
            // check if next token is "gopal" 
            System.out.println("" + scanner.hasNext("gopal")); 
  
            // find the last match and print it 
            System.out.println("" + scanner.match()); 
  
            // print the line 
            System.out.println("" + scanner.nextLine()); 
  
            // close the scanner 
            scanner.close(); 
        } 
  
        catch (IllegalStateException e) { 
            System.out.println("Exception caught is: " + e); 
        } 
    } 
}
輸出:
false
Exception caught is: java.lang.IllegalStateException: No match result available

參考: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#match()



相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 Scanner match() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。