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

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

Re: Regexp replacement question


From: Pascal J. Bourguignon
Subject: Re: Regexp replacement question
Date: Thu, 23 Apr 2015 11:52:28 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)

MBR <mbr@arlsoft.com> writes:

> I've been using Emacs regular expressions for ages, and I thought I
> had a pretty good command of them.  But I just found myself wanting to
> do something that seems like it should be fairly simple, and I can't
> figure out how to do it with regular expressions.  I'd like to be able
> to specify a repeat count in the replace string equal to the number of
> times a particular group in the search string matched.  For example,
> if I have a buffer containing one number per line, I can easily match
> all sequences of leading zeroes with the regexp:
>
>     ^0+
>
> I could identify that sequence of leading zeroes as group 1 with the regexp:
>
>     ^\(0+\)
>
> and then in the replacement string I can reference the string that
> group matched as \1.
>
> But what do I do if I want to replace leading zeroes with the same
> number of spaces.  E.G. if my file contains:
>
>     12345
>       123
>      7890
>         3
>
> I'd like to convert it to:
>
>     12345
>     __123
>     _7890
>     ____3
>
> (Actually, I'd like to convert leading zeroes to spaces, but I'm using
> underscore "_" instead of space to make it visible in this message.)
>
> To do that, I'd need to be able to specify a count in the replacement
> string.  Imagine there were a syntax applicable to replacement strings
> such that \{n\} meant repeat the previous character n times.  And
> similarly, imagine that \{\n\} meant repeat the previous character by
> however many times group n in the search string matched.  If I had
> that capability, I could search for:
>
>     ^\(0\)+
>
> and replace it with:
>
>     _\{\1\}
>
> I've read through the Emacs documentation, and I can't find anything
> that will allow me to convert leading zeroes to the same number of
> spaces, or vice versa.
>
> Ideas?
>
>    Mark Rosenthal
>    mbr@arlsoft.com <mailto:mbr@arlsoft.com>
>
>

M-x replace-regexp RET \<\(0+\) RET \,(make-string (length \1) 32) RET

-- 
__Pascal Bourguignon__                 http://www.informatimago.com/
“The factory of the future will have only two employees, a man and a
dog. The man will be there to feed the dog. The dog will be there to
keep the man from touching the equipment.” -- Carl Bass CEO Autodesk


reply via email to

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