Scanner(jdk API) :一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器。
Scanner 使用分隔符模式将其输入分解为标记,默认情况下该分隔符模式与空白匹配。然后可以使用不同的 next 方法将得到的标记转换为不同类型的值。
package test; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.regex.MatchResult; public class TestScanner { public static void main(String[] args) throws FileNotFoundException { // 键盘输入 Scanner sc = new Scanner(System.in); System.out.println(sc.nextInt()); System.out.println("---------------"); // 文本扫描 Scanner sc2 = new Scanner(new File("D://1.txt")); while (sc2.hasNextDouble()) { System.out.println(sc2.nextDouble()); } System.out.println("---------------"); // 正则解析 String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close(); System.out.println("---------------"); // 正则-匹配组 String input2 = "1 fish 2 fish red fish blue fish"; Scanner s2 = new Scanner(input2); s2.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"); MatchResult result = s2.match(); for (int i = 1; i <= result.groupCount(); i++) System.out.println(result.group(i)); s.close(); } }
//output 11 11 --------------- 12.2 12.2 0.11 345.121 11.1 --------------- 1 2 red blue --------------- 1 2 red blue
再来个例子,根据pattern字符串来匹配
package test; import java.util.Scanner; import java.util.regex.MatchResult; public class TestScanner2 { public static void main(String[] args) { String data = "127.0.0.1@21/10/2005\n" + "128.0.0.11@3/11/2006\n" + "129.132.111.111@4/2/2007\n" + "130.0.0.1@15/1/2008\n" + "[Next log section with different format]"; Scanner s = new Scanner(data); String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@(\\d{1,2}/\\d{1,2}/\\d{4})"; while(s.hasNext(pattern)) { s.next(pattern); MatchResult mr = s.match(); System.out.format("ip = %-15s,data= %10s\n",mr.group(1),mr.group(2)); } } }
//output ip = 127.0.0.1,data= 21/10/2005 ip = 128.0.0.11,data= 3/11/2006 ip = 129.132.111.111,data= 4/2/2007 ip = 130.0.0.1,data= 15/1/2008
总结:1)多种输入,File,input,System.in,String等
2)与正则结合使用
3)实现了Iterator接口