// $Id: regexmatch.java,v 1.2 2003/10/13 16:50:21 tomk Exp $ // http://www.bagley.org/~doug/shootout/ // contributed by Tom Kludy import java.io.*; import java.util.*; import java.util.regex.*; public class regexmatch { public static void main(String args[]) throws IOException, PatternSyntaxException { int n = (args.length > 0) ? Integer.parseInt(args[0]) : 1; LinkedList lines = new LinkedList(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while( (line = in.readLine()) != null ) lines.addLast(line); in.close(); Pattern pattern = Pattern.compile( "(?:^|[^\\d\\(])"+ // must be preceeded by non-digit "(?:\\((\\d\\d\\d)\\)|(\\d\\d\\d))"+// area code is 3 digits (match 1&2) "[ ]"+ // area code followed by one space "(\\d\\d\\d)"+ // match 3: prefix of 3 digits "[ -]"+ // separator is either space or dash "(\\d\\d\\d\\d)"+ // match 4: last 4 digits "(?:\\D|$)" // must be followed by a non-digit ); int count = 0; while(--n >= 0) { for (ListIterator li = lines.listIterator(); li.hasNext();) { Matcher matcher = pattern.matcher((String)li.next()); if (matcher.find()) { StringBuffer num = new StringBuffer("("); String areaCode = matcher.group(1); if ( areaCode == null ) areaCode = matcher.group(2); num.append(areaCode).append(") ").append(matcher.group(3)) .append("-").append(matcher.group(4)); if ( n == 0 ) System.out.println(++count + ": " + num); } } } } }