[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Tricky Regexp - How to insert a marker every 3rd number in a sequenc
From: |
John Mastro |
Subject: |
Re: Tricky Regexp - How to insert a marker every 3rd number in a sequence that begins with a certain delimiter |
Date: |
Sat, 6 Jun 2015 12:08:55 -0700 |
<gnuist006@gmail.com> wrote:
> tricky regexp
>
> How to insert a marker every 3rd number in a sequence that begins with
> a certain delimiter, and ends with a certain delimiter and its length
> is a multiple of three?
>
> I want to isolate sequences like this in a text and to work on them
> only.
>
> Given:-
>
> text
> text
> BEGIN N N N END
> text BEGIN N N N N N N END
> some text BEGIN N N N N N N N N N END
> text
> N N N N N N N
> text
>
> The sequences I want to work on start with BEGIN and end with END with
> exact multiple of 3 B's in between with only single space. I want to
> place a newline before every 3 B's. So the above text would transform
> to
>
> text
> text
> BEGIN
> N N N
> Z
> text BEGIN
> N N N
> N N N
> Z
> some text BEGIN
> N N N
> N N N
> N N N
> Z
> text
> N N N N N N N
> text
Is there a particular reason you want/need to use a (single) regular
expression? It doesn't seem like a good fit to me. Unless you're
somehow restricted to a single `replace-regexp', you may as well
use more of Emacs's toolbox.
Here's some quick-and-dirty Lisp (which, of course, uses regular
expressions) that works on your example but would need more work and
refinement to serve your general purpose.
(defun something ()
(interactive)
(save-excursion
(goto-char (point-min))
(while (re-search-forward "BEGIN" nil t)
(insert "\n")
(delete-horizontal-space)
(while (looking-at "\\(^\\| \\)N N N\\( \\|$\\)")
(goto-char (match-end 0))
(delete-horizontal-space t)
(insert "\n"))
(when (looking-at "END")
(replace-match "Z" nil nil nil 0)))))
--
john
Message not available