PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib_test/re_match.ml

http://github.com/avsm/ocaml-re
OCaml | 56 lines | 40 code | 5 blank | 11 comment | 7 complexity | 9ccbb51c8d6653e61eb086c869da9633 MD5 | raw file
Possible License(s): LGPL-2.1
  1. (*
  2. * $Id: re_match.ml,v 1.2 2001/10/03 15:04:59 vouillon Exp $
  3. * http://www.bagley.org/~doug/shootout/
  4. * from: Markus Mottl
  5. *)
  6. let rex =
  7. let three_digits = Re.seq [Re.digit; Re.digit; Re.digit] in
  8. Re.compile
  9. (Re.seq
  10. [(* Must be preceeded by a non-digit *)
  11. Re.alt [Re.bol; Re.compl [Re.digit; Re.char '(']];
  12. (* Area code *)
  13. Re.group (Re.alt [Re.seq [Re.char '('; three_digits; Re.char ')'];
  14. three_digits]);
  15. (* One space *)
  16. Re.char ' ';
  17. (* Prefix of 3 digits *)
  18. three_digits;
  19. (* Separator: either a space or a dash *)
  20. Re.set " -";
  21. (* Last for digits *)
  22. three_digits; Re.digit;
  23. (* Must be followed by a non-digit (or EOL) *)
  24. Re.alt [Re.eol; Re.compl [Re.digit]]])
  25. let foreach_line ?(ic = stdin) f =
  26. try while true do f (input_line ic) done with End_of_file -> ()
  27. let phones =
  28. let lines = ref [] in
  29. let ic = open_in "Input" in
  30. foreach_line ~ic (fun line -> lines := line :: !lines);
  31. close_in ic;
  32. List.rev !lines
  33. let check_phone cnt must_print line =
  34. try
  35. let matches = Re.exec rex line in
  36. let num = String.copy "(...) ...-...."
  37. and (pos, _) = Re.get_ofs matches 1 in
  38. let ofs = if line.[pos] = '(' then 1 else 0 in
  39. let pos = pos + ofs in
  40. String.blit line pos num 1 3;
  41. let pos = pos + ofs + 4 in
  42. String.blit line pos num 6 3;
  43. String.blit line (pos + 4) num 10 4;
  44. if must_print then Printf.printf "%d: %s\n" !cnt num;
  45. incr cnt
  46. with Not_found -> ()
  47. let n = if Array.length Sys.argv > 1 then int_of_string Sys.argv.(1) else 1;;
  48. for i = 2 to n do
  49. List.iter (check_phone (ref 1) false) phones
  50. done;
  51. List.iter (check_phone (ref 1) true) phones