Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all characters in a regex match with the same character in Vim

Tags:

regex

vim

I have a regex to replace a certain pattern with a certain string, where the string is built dynamically by repeating a certain character as many times as there are characters in the match.

For example, say I have the following substitution command:

%s/hello/-----/g

However, I would like to do something like this instead:

%s/hello/-{5}/g

where the non-existing notation -{5} would stand for the dash character repeated five times.

Is there a way to do this?

Ultimately, I'd like to achieve something like this:

%s/(hello)*/-{\=strlen(\0)}/g

which would replace any instance of a string of only hellos with the string consisting of the dash character repeated the number of times equal to the length of the matched string.

like image 612
beatgammit Avatar asked Sep 07 '11 18:09

beatgammit


People also ask

How do I match a pattern in Vim?

In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

Can you use regex to replace string?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.


2 Answers

%s/\v(hello)*/\=repeat('-',strlen(submatch(0)))/g
like image 149
Peter Rincker Avatar answered Sep 23 '22 02:09

Peter Rincker


As an alternative to using the :substitute command (the usage of which is already covered in @Peter’s answer), I can suggest automating the editing commands for performing the replacement by means of a self-referring macro.

A straightforward way of overwriting occurrences of the search pattern with a certain character by hand would the following sequence of Normal-mode commands.

  1. Search for the start of the next occurrence.

    /\(hello\)\+
    
  2. Select matching text till the end.

    v//e
    
  3. Replace selected text.

    r-
    
  4. Repeat from step 1.

Thus, to automate this routine, one can run the command

:let[@/,@s]=['\(hello\)\+',"//\rv//e\rr-@s"]

and execute the contents of that s register starting from the beginning of the buffer (or anther appropriate location) by

gg@s
like image 30
ib. Avatar answered Sep 26 '22 02:09

ib.