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

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

Regexp replacement question


From: MBR
Subject: Regexp replacement question
Date: Thu, 23 Apr 2015 05:54:54 -0400
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Thunderbird/24.4.0

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
    00123
    07890
    00003

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
   address@hidden <mailto:address@hidden>




reply via email to

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