In Clojure how can I convert a String to a number?

Solution 1:

This will work on 10px or px10

(defn parse-int [s]
   (Integer. (re-find  #"\d+" s )))

it will parse the first continuous digit only so

user=> (parse-int "10not123")
10
user=> (parse-int "abc10def11")
10

Solution 2:

New answer

I like snrobot's answer better. Using the Java method is simpler and more robust than using read-string for this simple use case. I did make a couple of small changes. Since the author didn't rule out negative numbers, I adjusted it to allow negative numbers. I also made it so it requires the number to start at the beginning of the string.

(defn parse-int [s]
  (Integer/parseInt (re-find #"\A-?\d+" s)))

Additionally I found that Integer/parseInt parses as decimal when no radix is given, even if there are leading zeroes.

Old answer

First, to parse just an integer (since this is a hit on google and it's good background information):

You could use the reader:

(read-string "9") ; => 9

You could check that it's a number after it's read:

(defn str->int [str] (if (number? (read-string str))))

I'm not sure if user input can be trusted by the clojure reader so you could check before it's read as well:

(defn str->int [str] (if (re-matches (re-pattern "\\d+") str) (read-string str)))

I think I prefer the last solution.

And now, to your specific question. To parse something that starts with an integer, like 29px:

(read-string (second (re-matches (re-pattern "(\\d+).*") "29px"))) ; => 29