yazz.com
yazz.com

Reputation: 58826

Clojure to remove non-numbers from a string

I have the following code to try to remove non-numbers froma string:

(apply str 
    (flatten 
        (map 
            (fn[x] 
                (if (number? x) x)) 
                "ij443kj"
        )
    )
)

But it always returns an empty string instead of "443". Does anyone know what I am doing wrong here and how I can get the desired result?

Upvotes: 5

Views: 6460

Answers (4)

Shawn Zhang
Shawn Zhang

Reputation: 1884

in case you will handling decimal

#(re-seq #"[0-9\.]+" "ij443kj")

Upvotes: 1

kubicfeat
kubicfeat

Reputation: 19

get the char's int values...

(map int (apply vector "0123456789"))

-> (48 49 50 51 52 53 54 55 56 57)

then fix it:

(defn my-int
[char]
(- (int char) 48))

now let's try this again, shall we?

(map my-int (apply vector "0123456789"))

-> (0 1 2 3 4 5 6 7 8 9)

and just to get a warm-and-fuzzy that they're integers...

(map #(* % 10) (map my-int (apply vector "0123456789")))

-> (0 10 20 30 40 50 60 70 80 90)

(reduce + (map my-int (apply vector "0123456789")))

-> 45

Upvotes: 1

Julien Chastang
Julien Chastang

Reputation: 17784

There is an even simpler way, use a regular expression:

(.replaceAll "ij443kj" "[^0-9]" "")

Upvotes: 9

deong
deong

Reputation: 3870

number? doesn't work that way. It checks the type. If you pass it a character, you'll get back false every time, no matter what the character is.

I'd probably use a regular expression for this, but if you want to keep the same idea of the program, you could do something like

(apply str (filter #(#{\0,\1,\2,\3,\4,\5,\6,\7,\8,\9} %) "abc123def"))

or even better

(apply str (filter #(Character/isDigit %) myString))

Upvotes: 18

Related Questions