4

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!

1 Answer 1

7

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) . '"];'/
Sign up to request clarification or add additional context in comments.

3 Comments

Your code works, except for the regex (which OP provided). All else being equal, it should start with :%s/\([A-z ]\+\)/ to get the output he wants based on his sample input. Upvoted!
I think it still works, it just has an extra group in there that isn't necessary. Unfortunately I can't test it at the moment.
Odd, it didn't work for me before, but does now. Sorry for the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.