Probably, the most basic and pervasive tool for cleaning data of any kind is regular expressions. Although they're sometimes overused, often regular expressions truly are the best tool for the job. Moreover, Clojure has built-in syntax for compiled regular expressions, so they are convenient too.
In this example, we'll write a function that normalizes US phone numbers.
For this recipe, we will need to have the
clojure.string
library available for our script or REPL. The expression will be as follows:
(require '[clojure.string :as string])
For this recipe, let's define the regular expression, using the following:
(def phone-regex #"(?x) (\d{3}) # Area code. \D{0,2} # Separator. Probably one of \(, \), \-,\space. (\d{3}) # Prefix. \D? # Separator. (\d{4}) ")
Now, we'll define a function that uses that regular expression to pull apart a string containing a phone number and put it back together in...