当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。