6

I am looking for a way to convert one word to another while "capturing" the case of the match that is substituted. An example:

I have the text:

Begin the beginning

Now I want to convert this to

End the ending

To do so I need a command like the one below:

s/([Bb]egin/ [CASE OF CAPTURE][Ee]nd/g

But then with a correctly working [CASE OF CAPTURE][Ee] part.

How do we get the case of the capture (being upper or lowercase begin) and substitute with same (upper or lowercase end)?

  • From stackoverflow: stackoverflow.com/q/782511/4751065 – Sakari Cajanus Jan 10 '16 at 11:44
  • @SakariCajanus Thank you. I see that without a plugin it is quite cumbersome. Guess I have to find out how to use plugins in ViEmu. – Erwin Rooijakkers Jan 10 '16 at 11:47
  • I understand it's just an example, but sometimes you might just want to do 2 substitutions instead of one. – PhilippFrank Jan 11 '16 at 7:22
5

You can do it like this:

:s/\([Bb]\)egin/\=printf("%snd", submatch(1)==#'B'?'E':'e')/

This checks in the replacement part of the :s command, what the case of the first subgroup was and either returns an upper 'e' or a lower 'e'.

  • And a /g at the end ;). Note that "Begin of the beginning" turns into "End of the endning", but that was my mistake. Thank you. :) – Erwin Rooijakkers Jan 10 '16 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.