import java.io.*; import java.util.*; import java.util.regex.*; // When we pass this source file to this program on the command line, the // regular expression will find this phone number, and the one at the bottom. // (212)555-1212 // // This number, however, since it is not a phone number, will not match. // 333 9999 public class Phone { public static void main(String[] args) throws Exception { // Note that \+ matches a +, \( and \) match the characters ( and ) // In regulare expressions, all letters match them selves, and // all punctuation characters with a backslash in front match themselves. // Thus, a \* matches a *. String pat = "(\\+\\d)?\\((\\d\\d\\d)\\)(\\d\\d\\d)-(\\d\\d\\d\\d)"; Scanner s = new Scanner(new File(args[0])); while(s.hasNextLine()) { if(s.findInLine(pat) != null) { MatchResult m = s.match(); // The country code will be null if one is not supplied. System.out.println("Country Code: "+m.group(1)); System.out.println("Area Code: "+m.group(2)); System.out.println("Prefix: "+m.group(3)); System.out.println("Line Number: "+m.group(4)); System.out.println(); } s.nextLine(); } } // +1(888)111-2222 }