[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: extract lines with regexp
From: |
Raymond Wiker |
Subject: |
Re: extract lines with regexp |
Date: |
Mon, 04 May 2009 19:44:59 +0200 |
User-agent: |
Gnus/5.1008 (Gnus v5.10.8) XEmacs/21.5-b28 (darwin) |
Ted Zlatanov <tzz@lifelogs.com> writes:
> On Thu, 30 Apr 2009 11:57:06 -0700 (PDT) Xah Lee <xahlee@gmail.com> wrote:
>
> XL> (let (p1 p2)
> XL> (save-excursion
> XL> (goto-char (point-min))
> XL> (search-forward-regexp "^A.+$") ; begin pattern
> XL> (setq p1 (point)) ; save cursor pos
> XL> (search-forward-regexp "theq() :") ; ending pattern
> XL> (backward-char 8)
> XL> (setq p2 (point)) ; save cursor pos
> XL> (setq mytext (buffer-substring p1 p2))
> XL> )
> XL> )
>
> I don't think your first patten is exactly what the OP needed.
>
> You can use (forward-line -1) to move the point back to the previous
> line, and (beginning-of-line -1) to move to the beginning of the
> previous line. Also, you don't need search-forward-regexp the second
> time, just search-forward will work. Plus, of course, (backward-char 8)
> is just asking for trouble.
>
> Anyhow, regular expressions can handle multiple lines just fine:
>
> A
> theq() :
> non
> B
> theq() :
>
> (save-excursion
> (goto-char (point-min))
> (while (re-search-forward "\\(.*\\)\ntheq() :" nil t)
> (message (match-string 1))))
>
> will produce "A" and "B"
A slightly more elaborate version (not necessarily more
correct, but with a few more functions to ponder :-)
;;; -------------------------------------------------
(defun collect-all-before (pattern)
(interactive "sPattern: ")
(let (ret)
(while (re-search-forward pattern nil t)
(save-excursion
(if (zerop (forward-line -1))
(push (buffer-substring (point)
(progn
(forward-line 1)
(point)))
ret))))
(with-output-to-temp-buffer "*tmp*"
(set-buffer "*tmp*")
(dolist (elt (nreverse ret))
(insert elt)))))
;;; -------------------------------------------------
(push ...) and (dolist ...) are from a package that tries to
make Emacs-Lisp a bit more like Common Lisp, and can be trivially
replaced with native Emacs-Lisp constructs.