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

前端 未结 2 782
醉梦人生
醉梦人生 2021-01-01 19:03

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 characte

相关标签:
2条回答
  • 2021-01-01 19:10
    %s/\v(hello)*/\=repeat('-',strlen(submatch(0)))/g
    
    0 讨论(0)
  • 2021-01-01 19:13

    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
    
    0 讨论(0)
提交回复
热议问题