I have a substitute expression to find words beginning with a dollar signs and capture them like this:


However there are a lot of escape sequences in the regular expression (4). Is there a way to avoid so many escapes in this expression?

  • What are you trying to do here? Why even bother capturing in this case? This can be simplified by :%s/$\k\+//g. 29% shorter! – Peter Rincker Feb 20 '18 at 16:34
  • @PeterRincker The word after the $ is being captured. The use of the capture is not shown. – Tyler Durden Feb 20 '18 at 16:36

You could use a "very magic" expression:


(See :help \v)

I'd also note that your expression doesn't do what you say you want it to do. For example, it includes the "bar" in this match: "$foo bar".

Maybe try this instead:

| improve this answer | |
  • Hmm, I thought that the > symbol was supposed to stop the match at a word boundary. I tried using S+ and it failed to match the word. – Tyler Durden Feb 20 '18 at 16:46
  • It does. Just not the word boundary you're expecting. For that, you need either to use a non-greedy match, or something easier to type, such as what I or @PeterRincker suggest. My suggestions works correctly for me. Are you sure you typed exactly what I wrote? – Rich Feb 20 '18 at 16:48
  • @TylerDurden, .* is greedy by default. This means it will capture everything up to a word boundary. So capturing all the words on a line until it finds a word boundary. Use .\{-} instead for an un-greedy variant. Or use something like \k*/\w* to avoid the \> in the first place – Peter Rincker Feb 20 '18 at 16:48
  • I tried :%s/\v\$(\k+) and it does not match – Tyler Durden Feb 20 '18 at 16:52
  • Please give us some example text so we can help you better. Also \k is based off of 'iskeyword' which can change depending on your 'filetype'. So \w maybe better here – Peter Rincker Feb 20 '18 at 16:56

You can use 'magic' or \zs to reduce the need for escaping:


I am using \k to capture anything that looks like a keyword as that will more than likely be what you want and will remove the need for \>. With \zs your capture group is now \0/&. The $ often does not need to be escaped.

Note: :%s/$\zs.*\>//g may be too greedy if you want to capture just $foo. It will instead capture $foo bar. This maybe desired.

For more help see:

:h /\zs
:h /\v
:h 'magic'
| improve this answer | |

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.