Parsing is the process of splitting a string into smaller substrings (a.k.a. tokens).
import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * Changing the delimiter on the Scanner. */ public static void parseColonDelin(Scanner sc) { sc.useDelimiter(":|\n"); while(sc.hasNext()) { String token = sc.next(); System.out.println("[" + token + "]"); } } /* * Reading each line of input as a String, splitting the String, * and putting the tokens in an array. */ public static void parseTabDelin(Scanner sc) { if (!sc.hasNext()) return; while(sc.hasNext()) { String input = sc.nextLine(); String[] tokens = input.split("\t|\n"); for(String token : tokens) System.out.println("[" + token + "]"); } } /* * Reading each line as a String, creating a regex Pattern, * and using a Matcher to find instances of the pattern in * the String. */ public static void parseFixedLen(Scanner sc) { if (!sc.hasNext()) return; while(sc.hasNext()) { String input = sc.nextLine(); Pattern p = Pattern.compile("[PKHT]\\d\\d"); Matcher m = p.matcher(input); while (m.find()) { String token = m.group(); System.out.println("[" + token + "]"); } } }
© 2017 – 2019, Eric. All rights reserved.