1

Dear fellow Developers,
I would like to quote variables having @ inside like test@mail.org, but not starting with @ like @var1, @var2.
Does Vi/Vim/Neovim have any option to inspect the matched pattern and create a pre- and postfix to test@mail.org: "test@mail.org" ?
:%s/ [a-zA-Z0-9]+@[a-zA-Z0-9]* / \"*\" /
does not work due to \"*\".

If Vi/Vim/Neovim has no such feature, what tools would you recommend for portability? I know C++ has a feature to inspect the matched regex as a string for manipulation, but I would like to have a more pluggable solution for vim.

1

Try using \0 to insert the contents of the match in the substitution:

:%s/\<[a-zA-Z0-9.]\+@[a-zA-Z0-9.]*\>/"\0"/g

Note that, given that you gave an example of an email address, I added . to your character classes so that the expression will match these, but it won't only match email addresses. e.g. It would match a@a.

I also changed the white spaces into start/end word atoms: \<, \> so that it will successfully match email addresses abutting punctuation, and added a g flag so that more than one match can be found on each line.

  • Ive always used & because it’s easier to type than \0—are the functionally equivalent (ie worth suggesting as an alternative in the answer)? Or is there a subtle difference (and i should stop using &)? – D. Ben Knoble Oct 5 at 0:58
  • @D.BenKnoble From a short glimpse at the source I would say '&' and '\0' are the equivalent. – Ralf Oct 5 at 12:09
  • @D.BenKnoble The two are equivalent. I didn't mention & in my answer because I don't think it really adds much benefit to know two different ways of doing it, and it makes the answer more complicated. I personally use \0 because a). I learned it first b). I like the relation to \1 et al. and the similarity with awk, and c). as someone who doesn't type "correctly" it's not any harder to type than &. (In fact, it's almost identical, but slightly easier because it's not a chord) ;) – Rich Oct 5 at 13:03

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.