user1327477
user1327477

Reputation:

vim sub-replace expression with more text

So I was searching for a way to take something like this

Two words
Three Words Here

And replace it with this

Twowords = myHash["Two words"];
ThreeWordsHere = myHash["Three Words Here"];

I found this question, which led me to the sub-replace commands, and I came to something like this.

%s/\(\([A-z ]\)\+\)/\=substitute(submatch(1), ' ', '', 'g')/

Now this will get the match without spaces to appear, but there will be nothing after the equals sign. Adding in text after the substitute expression results in an "E51: Invalid Expression" error.

My question is: is there a way to end an expression, and add more text to the :s command? Something like this.

%s/\(\([A-z ]\)\+\)/\=substitute(submatch(1), ' ', '', 'g') = myHash["\1"];/

I have not been able to find anything. I've looked at :help sub-replace-\= and other sources online. Thanks!

Upvotes: 4

Views: 2568

Answers (1)

Randy Morris
Randy Morris

Reputation: 40927

You almost had it.

Everything after an \= atom has to be an expression, therefore you need to concatenate strings together and use submatch() again. Using the regex you already provided:

:%s/\(\([A-z ]\)\+\)/\=substitute(submatch(1), ' ', '', 'g') . ' = myHash["' . submatch(1) . '"];'/

Upvotes: 6

Related Questions