help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to parse a string?


From: Greg Hill
Subject: Re: How to parse a string?
Date: Thu, 1 May 2003 11:02:24 -0700

At 11:56 AM +0200 5/1/03, Francois Fleuret wrote:
But is there a generic way to do such a thing ? No scanf equivalent
around ?

Not as standard Emacs Lisp, but no doubt someone has written their own. I'm surprised nobody has replied by giving you a web page where you could find one.

It wouldn't be hard to write one for yourself, and then you can make it behave any way you like. Here is something quick and dirty I just hacked together to demonstrate what I mean. It takes a "format string" as the first argument, and the string to be parsed as the second. Each character in the format string tells how to translate one "word" in the string to be parsed, where:

i = integer
f = float
n = number (integer or float, don't care)
s = string
anything else = skip

(defun scanf (format string)
  (let ((list nil) fmt word)
    (setq string (split-string string)
          format (split-string format ""))
    (while (and string format)
      (setq word (pop string)
            fmt (pop format))
      (cond ((equal fmt "i")
             (setq word (floor (string-to-number word))))
            ((equal fmt "f")
             (setq word (float (string-to-number word))))
            ((equal fmt "n")
             (setq word (string-to-number word)))
            ((not (equal fmt "s"))
             (setq word nil)))
      (if word (setq list (append list (list word)))))
    list))


Use it like this:

(scanf "ifsxnn" "1 2.3 word skip 4 5.6")
==> (1 2.3 "word" 4 5.6)

Now go ahead and be a real Emacser. Cook up your own function work any way you like.

--Greg




reply via email to

[Prev in Thread] Current Thread [Next in Thread]