Determine if a string is numeric: Difference between revisions

→‎{{header|Clojure}}: Added function which works with any Clojure numeric literal string
(→‎{{header|Clojure}}: Added function which works with any Clojure numeric literal string)
Line 1,158:
This works with any sequence of characters, not just Strings, e.g.:
<lang clojure>(numeric? [\1 \2 \3]) ;; yields logical true</lang>
 
Clojure has a fairly rich set of numeric literals, including Ratios, BigInts and BigDecimals. The Clojure reader will attempt to read any form starting with a digit (optionally preceded by a '+' or '-') as a number. So the following checks to see if such a read is successful:
<lang clojure>
(require '[clojure.edn :as edn])
(import [java.io PushbackReader StringReader])
 
(defn number-string? [s]
(boolean
(when (and (string? s) (re-matches #"^[+-]?\d.*" s))
(let [reader (PushbackReader. (StringReader. s))
num (try (edn/read reader) (catch Exception _ nil))]
(when num
; Check that the string has nothing after the number
(= -1 (.read reader)))))))
</lang>
<lang clojure>
user=> (number-string? "2r101010")
true
user=> (number-string? "22/7")
true
</lang>
 
=={{header|COBOL}}==
Anonymous user