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)?

3
  • From stackoverflow: stackoverflow.com/q/782511/4751065 Jan 10, 2016 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. Jan 10, 2016 at 11:47
  • I understand it's just an example, but sometimes you might just want to do 2 substitutions instead of one. Jan 11, 2016 at 7:22

1 Answer 1

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'.

1
  • 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. :) Jan 10, 2016 at 19:54

Your Answer

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

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