📜  Java中的扫描仪 match() 方法与示例

📅  最后修改于: 2022-05-13 01:55:11.905000             🧑  作者: Mango

Java中的扫描仪 match() 方法与示例

Java.util.Scanner类的match()方法返回此扫描器执行的最后一次扫描操作的匹配结果。

句法:

public MatchResult match()

返回值:该函数返回最后一次匹配操作的匹配结果

异常:如果没有执行匹配,或者最后一次匹配不成功,该函数将抛出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
    {
  
        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!

方案二:演示 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: Java/util/Scanner.html#match()