From: T. V. Raman
Subject: Recognizing strings that are numbers: eg "123.33"
Date: 
Message-ID: <1992Sep29.132811.921@cs.cornell.edu>
Hi!

I need to write a function number-string? which given a string returns
t if the string is in fact a number inside quotes. Number here is a
number as would be found in text eg 12 or 12.3 or 12,325 and not
scientific notation etc.

A naive way of writing this is
(defun NUMBER-STRING? (string) 
  "checks if string is a quoted number"
  (and
   (stringp string)
   (numberp (read-from-string string)))
  )


The above function is however unsafe and quite inelegant when it runs
into unexpected strings eg
(number-string? "'") or (number-string? ".") etc.

What is the alternative to using read-from-string here?

Thanks,

--Raman
-- 
   T. V. Raman <·····@cs.cornell.edu>Tel: (607)255-9202  R 272-3649
                       Office: 4116 Upson Hall,
Department of Computer Science, Cornell University Ithaca NY 14853-6201
                Res: 226 Bryant Avenue Ithaca NY 14850

From: Barry Margolin
Subject: Re: Recognizing strings that are numbers: eg "123.33"
Date: 
Message-ID: <1a9v6iINN537@early-bird.think.com>
In article <····················@cs.cornell.edu> ·····@cs.cornell.edu (T. V. Raman) writes:
>I need to write a function number-string? which given a string returns
>t if the string is in fact a number inside quotes. Number here is a
>number as would be found in text eg 12 or 12.3 or 12,325 and not
>scientific notation etc.
>
>A naive way of writing this is
>(defun NUMBER-STRING? (string) 
>  "checks if string is a quoted number"
>  (and
>   (stringp string)
>   (numberp (read-from-string string)))
>  )

(defun number-string? (string)
  (and (stringp string)
       (numberp (ignore-errors (read-from-string string)))))

is better.  Note, however, that this will return true for numbers in
scientific notation, while it will return false for 12,325, because the
Lisp reader doesn't support commas inside numbers.

Also, it will return true for "123 foo", since READ-FROM-STRING will stop
at the delimiter.  To catch this you'll have to make use of the second
return value from READ-FROM-STRING, which is the index where it stopped
reading, and compare it to the length of the string.

Beyond this, I think you'll have to write your own little lexer that
recognizes all the number formats you wish to support.
-- 
Barry Margolin
System Manager, Thinking Machines Corp.

······@think.com          {uunet,harvard}!think!barmar
From: Kent M Pitman
Subject: Re: Recognizing strings that are numbers: eg "123.33"
Date: 
Message-ID: <19920929194155.2.KMP@PLANTAIN.SCRC.Symbolics.COM>
I'd probably PARSE-INTEGER, iterating on commas and dots, rather than
READ since the required notation is specialized.

If you use READ-FROM-STRING, the IGNORE-ERRORS is right, but you should
also bind *READ-EVAL* to suppress any trojan horses that might creep in
due to use of #. in the string to be tested.