Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure to remove non-numbers from a string

Tags:

clojure

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?

like image 1000
yazz.com Avatar asked May 18 '11 14:05

yazz.com


People also ask

How do I remove non numeric characters from a string?

In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.


1 Answers

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))
like image 87
deong Avatar answered Nov 15 '22 06:11

deong