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

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

Re: string to list or string to array


From: Pascal J. Bourguignon
Subject: Re: string to list or string to array
Date: Sun, 21 Oct 2012 13:16:37 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.4 (gnu/linux)

Swami Tota Ram Shankar <address@hidden> writes:

> Friends, I am trying to read text from a file opened in emacs and
> recognize it as array or list so that I can do some vector additions
> using mapcar.
>
> I am mainly stuck at the stage of converting the string text to array
> or list.
>
> The method which I use to locate the text is "looking-at" function and
> the regexp works.
>
> (when (looking-at "[[0-9.+-\\ ]+]")
                     ^^
                     12

The character 1 has the meaning you'd want the character 2 to have.

Your regexp parses as:

     one or more of any character in "[0123456789.+- "
     followed by "]".

You want:

      (looking-at "\\[[0-9.+-\\ ]+\\]")

The third backslash is optional, but I add it for clarity.

> some code that is to play around for debugging and messaging and
> checking the match
> (forward-char (+ (string-width (match-string 0)) 1))
> (setq V (match-string 0))
> (setq V (intern (match-string 0)))
>
>
> The cursor is placed on the start bracket, ie "["
>
> and text looks like for example array of indefinite length
>
> [17.16 -17.16 17.16 17.16 17.16 17.16 17.16 17.16]
>
>
> Please suggest some different solutions that can take the string
> matched, match-string for example and convert to a list or an array on
> which I can do mapcars or lambdas.

Since the syntax of this text is exactly the printed representation of
an emacs lisp vector, you can read it directly with read.

(defun get-vectors-from-buffer ()
   (let ((vectors '()))
     (goto-char (point-min))
     (while (re-search-forward "\\[[0-9.+-\\ ]+\\]" nil t)
        (goto-char (match-beginning 0))
        (push (read (current-buffer)) vectors))
     (nreverse vectors)))

;; [1 2 3.0] [4 5 6]
;; [7 +8 -9]

(get-vectors-from-buffer)
--> ([[0-9\.+-\\] +]
     [[0-9\.+-\\] +\\]
     [17.16 -17.16 17.16 17.16 17.16 17.16 17.16 17.16]
     [[0-9\.+-\\] +\\]
     [1 2 3.0]
     [4 5 6]
     [7 8 -9])

-- 
__Pascal Bourguignon__                     http://www.informatimago.com/
A bad day in () is better than a good day in {}.


reply via email to

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