Java Scanner match()方法及示例

来源:这里教程网 时间:2026-02-17 21:08:13 作者:

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();    }}

输出:

truejava.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);        }    }}

输出:

falseException caught is: java.lang.IllegalStateException: No match result available

**参考资料: ** https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#match()

相关推荐