6

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.

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.

  • Nice points on the leading zeroes and the floating point approximations – Dan Jul 30 '15 at 21:17
  • 1
    You can use string-match-p instead of wrapping with save-match-data – npostavs Jul 31 '15 at 5:35
7

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

(cl-parse-integer "23K") ; errors
(cl-parse-integer "23K" :junk-allowed t)
23
  • This allows nonpositive integers. – Gilles Jul 30 '15 at 21:20
  • 2
    It also allows you to check for them with normal numeric comparison. (< (cl-parse-integer "23K" :junk-allowed t) 0) – Archenoth Jul 30 '15 at 21:31
  • @Gilles yes, but I assumed it to be trivial to write. I doubt there's a specialized function for positive integers only (and probably if there was one, zero would be still treated as positive). – wvxvw Jul 31 '15 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.