[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How to read an integer from the minibuffer
From: |
Emanuel Berg |
Subject: |
Re: How to read an integer from the minibuffer |
Date: |
Tue, 16 Nov 2021 10:38:23 +0100 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/29.0.50 (gnu/linux) |
Yuri Khan wrote:
> I was going to suggest piggybacking on the JSON parser, but
> it has the same bug:
>
> M-: (json-read-from-string "123foo")
> ⇒ 123 (#o173, #x7b, ?\{)
>
> Fortunately, json-read-from-string is simple enough that you can copy
> and modify it:
>
> -(defun json-read-from-string (string)
> +(defun json-read-from-string-strict (string)
> "Read the JSON object contained in STRING and return it."
> (with-temp-buffer
> (insert string)
> (goto-char (point-min))
> - (json-read)))
> + (prog1 (json-read)
> + (unless (eobp) (error "Trailing garbage")))))
>
> You still get some whitespace skipping though.
(defun string-to-number-number (str)
(let ((s (string-trim str)))
(if (string-match "^[+-]\\{0,1\\}\\(0+\\|0*\\.0+\\)$" s)
0
(let ((num (string-to-number s)))
(when (and (not (zerop num))
(string-match
"^[+-]\\{0,1\\}\\([[:digit:]]+\\|[[:digit:]]*\\.[[:digit:]]+\\)$" s) )
num) ))))
;; (string-to-number-number " 10") ; 10
;; (string-to-number-number " 1.5") ; 1.5
;; (string-to-number-number " +0") ; 0
;; (string-to-number-number " 0") ; 0
;; (string-to-number-number " -0.0") ; 0
;; (string-to-number-number " -1.5") ; 1.5
;; (string-to-number-number "-10") ; -10
;; (string-to-number-number "123this used to work") ; nil
;; (string-to-number-number "not a number") ; nil
--
underground experts united
https://dataswamp.org/~incal
Re: How to read an integer from the minibuffer, Marcin Borkowski, 2021/11/12
- Re: How to read an integer from the minibuffer, Emanuel Berg, 2021/11/16
- Re: How to read an integer from the minibuffer, Yuri Khan, 2021/11/16
- Re: How to read an integer from the minibuffer,
Emanuel Berg <=
- Re: How to read an integer from the minibuffer, Yuri Khan, 2021/11/16
- Re: How to read an integer from the minibuffer, Emanuel Berg, 2021/11/16
- Re: How to read an integer from the minibuffer, Yuri Khan, 2021/11/16
- Re: How to read an integer from the minibuffer, Emanuel Berg, 2021/11/16
- Re: How to read an integer from the minibuffer, Emanuel Berg, 2021/11/16