Database Reference
In-Depth Information
We also only need to have the clojure.string library available for our script or REPL.
We will get this by using:
(require '[clojure.string :as string])
How to do it…
1. First, let's deine a regular expression:
(def phone-regex
#"(?x)
(\d{3}) # Area code.
\D{0,2} # Separator. Probably one of \(, \), \-, \space.
(\d{3}) # Prefix.
\D? # Separator.
(\d{4})
")
2.
Now, we'll deine a function that uses this regular expression to pull apart a string
that contains a phone number and put it back together in the form of (999)555-
1212 . If the string doesn't appear to be a phone number, it returns nil :
(defn clean-us-phone [phone]
(when-let [[_ area-code prefix post]
(re-find phone-regex phone)]
(str \( area-code \) prefix \- post)))
3.
The function works the way we expected:
user=> (clean-us-phone "123-456-7890")
"(123)456-7890"
user=> (clean-us-phone "1 2 3 a b c 0 9 8 7")
nil
How it works…
The most complicated part of this process is the regular expression. Let's break it down:
F (?x) : This is a lag that doesn't match anything by itself. Instead, it allows you to
spread out the regular expression. The lag will ignore whitespaces and comments.
Writing regular expressions in this way makes them considerably easier to read and
work with, especially when you are trying to remember what it does after six months.
F (\d{3}) : This matches three digits.
F \D{0,2} : This matches zero to two non-numeric characters. This is to allow optional
separators between the area code and the preix.
 
Search WWH ::




Custom Search