Search code examples
clojure

Phone number regular expressions


Included is some code that can find a single number such as "555-555-5555" in a string. But I'm not quite sure how to extend the code to find all phone numbers within a string. The code stops after it has found the first number...

(defn foo [x]
(re-find (re-matcher #"((\d+)-(\d+)-(\d+))" x)))

Is there a way to extend this code to find all numbers within a string?


Solution

  • re-seq returns a sequence of all the matches to a regex in a string:

    user> (defn foo [x] (re-seq #"\d+-\d+-\d+" x))                  
    #'user/foo 
    
    user> (foo "111-222-3333 555-666-7777")                         
    ("111-222-3333" "555-666-7777")   
    
    user> (foo "phone 1: 111-222-3333 phone 2: 555-666-7777")       
    ("111-222-3333" "555-666-7777") 
    

    So it will keep going until it finds all the phone numbers in the string.