Reman
Reman

Reputation: 8109

Vim Regex substitute question

I'm trying to replace in VIM all multiple "-" characters (from the start of lines) with "="

p.e. replace "-----" with "====="
or replace "----------" with "=========="

I created this regex:

%s/^-\{2,}/=  ????/g

Does anyone know how I can replicate the "=" substitution? (what do I have to put after "=")

Upvotes: 3

Views: 631

Answers (3)

Raimondi
Raimondi

Reputation: 5303

Try this:

:%s/^-\{2,}/\=substitute(submatch(0), '-','=','g')/

or:

:%s/^-\{2,}/\=repeat('=',len(submatch(0)))/

See :help sub-replace-\= for more details.

Upvotes: 5

sidyll
sidyll

Reputation: 59277

Technically, %s/-/=/g does the job, but on the entire file, in every -.

If the lines you want to substitute do start with - I'd do it this way:

g/^-/s/-/=/g

Or, if you have some space before the first -:

g/^\s*-/s/-/=/g

The remaining problem arrives in lines like this:

----------- the-composite-word

They turn into:

=========== the=composite=word

To solve that, there are many ways. I not that master to suggest a very general way, but this may work for dashes between words:

g/^-/s/\w\@<!-/g

Upvotes: 2

eykanal
eykanal

Reputation: 27017

I'm sure there's a better answer, but practically speaking, I would do this as two separate operations just for simplicity:

%s/--/==/g
%s/=-/==/g

First replace all double occurrences, which would turn ----- into ====-. Then fix the leftovers (=-) using the second. I would love to see the more elegant answer, though, if it is possible to do.

Upvotes: 2

Related Questions