7

I'm trying to test for whether a string contains a positive integer (1, 2, 3, ...). By "string contains" I mean the string is only numbers (e.g. "1", "12", "123" but not "0", "1.1", "1a", "a1").

My first thought was to test the type and check if it is an integer but first I need to convert to numeric.

(typep (string-to-number "23K") 'integer)
;; t

This doesn't work because string-to-number ignores any trailing characters.

Then I thought I'd use regular expressions to test that every character is in [0-9].

(equal (nth 0 (re-seq "[0-9]+" "23K")) "23K")

where re-seq is taken from this post and searches for every occurrence of the regular expression (first arg) in the second arg.

Combining that with a test for the number being greater than 0 I end up with this:

(and (equal (nth 0 (re-seq "[0-9]+" "23K")) "23K") 
     (> (string-to-number "23K") 0) )

I'm pretty new to lisp programming so I'm wondering if there is a simpler way to do this.

Stefan Avey
  • 228
  • 2
  • 7

2 Answers2

8

In cl package there's cl-parse-integer:

(cl-parse-integer "23K") ; errors
(cl-parse-integer "23K" :junk-allowed t)
23
wvxvw
  • 11,222
  • 2
  • 30
  • 55
8

You can use a regular expression to recognize positive integers written in decimal expansion: they are the strings that consist only of decimal digits, where at least one of the digits is nonzero.

(string-match "\\`[0-9]*[1-9][0-9]*\\'" my-string)

This allows leading zeros (e.g. "0123"); if you don't want that, insist that a nonzero digit comes first.

(string-match "\\`[1-9][0-9]*\\'" my-string)

If you use regular expressions for other things in the same piece of code, save the match data around your test.

(save-match-data
  (string-match "\\`[0-9]*[1-9][0-9]*\\'" my-string))

Note that if you try to convert the string to an integer with string-to-int, Emacs may make a floating point approximation if the integer is too large. With parse-integer, you'll get an integer but with wraparound at 2N where N is the number of bits in an integer in your version of Emacs.