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

前端 未结 13 694
别跟我提以往
别跟我提以往 2020-12-12 15:34

I have various strings, some like \"45\", some like \"45px\". How how I convert both of these to the number 45?

13条回答
  •  臣服心动
    2020-12-12 16:00

    For simple cases you can just use a regex to pull out the first string of digits as mentioned above.

    If you have a more complicated situation you may wish to use the InstaParse library:

    (ns tst.parse.demo
      (:use tupelo.test)
      (:require
        [clojure.string :as str]
        [instaparse.core :as insta]
        [tupelo.core :as t] ))
    (t/refer-tupelo)
    
    (dotest
      (let [abnf-src            "
    size-val      = int / int-px
    int           = digits          ; ex '123'
    int-px        = digits <'px'>   ; ex '123px'
          = 1*digit         ; 1 or more digits
           = %x30-39         ; 0-9
    "
        tx-map        {:int      (fn fn-int [& args]
                                   [:int (Integer/parseInt (str/join args))])
                       :int-px   (fn fn-int-px [& args]
                                   [:int-px (Integer/parseInt (str/join args))])
                       :size-val identity
                      }
    
        parser              (insta/parser abnf-src :input-format :abnf)
        instaparse-failure? (fn [arg] (= (class arg) instaparse.gll.Failure))
        parse-and-transform (fn [text]
                              (let [result (insta/transform tx-map
                                             (parser text))]
                                (if (instaparse-failure? result)
                                  (throw (IllegalArgumentException. (str result)))
                                  result)))  ]
      (is= [:int 123]     (parse-and-transform "123"))
      (is= [:int-px 123]  (parse-and-transform "123px"))
      (throws?            (parse-and-transform "123xyz"))))
    

提交回复
热议问题