Skip to main content
  1. Posts/

Nifty Nvim/Vim Techniques That Make My Life Easier -- Series 11

··376 words·2 mins·
Nvim Regex
Table of Contents

This is the 11th post of my post series on nifty Nvim/Vim techniques that will make my editing experience easier.

Click here to check other posts in this series.

Move lines matching a pattern together?
#

Use command :g/pattern/normal ddGp.

Here we use the :global command. It will apply the command :normal ddGp (which is deleting current line and paste it at the bottom) for each line matching pattern.

Another way to do this is to use :move together with :global command:

:[range]m[ove] {address}          *:m* *:mo* *:move* *E134*
          Move the lines given by [range] to below the line
          given by {address}.

Now the complete command to do this task is :g/pattern/m$ ($ means the last line of a buffer).

At the end, all lines matching pattern will be moved to the end of the buffer.

Ref:

Show trailing whitespace
#

We need to first define a highlight group for it and then match a pattern to use this highlight group:

highlight TrailingWhitespace ctermbg=red guibg=red

call matchadd("TrailingWhitespace", '\v\s+$')

We’d better use single quote pattern to avoid backslash hell, otherwise, escaping the pattern will be a pain. If we use double quote, \s won’t work, we have to escape backslash, see also :h literal-string.

Flip a 01 string quickly
#

To flip a 01 string (i.e., turn 0 to 1 and turn 1 to 0), we can use sub-replace-expression which is really powerful:

:s/\v(0|1)/\=submatch(0)==0?1:0/g

Or we can also use this (source here):

:s/\v(0|1)\=1-submatch(0)/g

Ref:

Search lines not starting with a pattern
#

This is a perfect example where using look around regex solves it neatly. For example, to search for lines not starting with foo, use the following search expression:

/\v^(foo)@!

A teardown of this expression:

  • \v: magic regex in vim, see also :h \v. We use \v to simplify writing regex in vim and make it more like PCRE.
  • ^: start of a line
  • (foo)@!: @! is the vim syntax for negative lookahead. This expression means that the previous expression should not be followed by foo, we group foo in Vim using parentheses.

Ref:

Related

How to Match Non-greedily in Nvim/Vim
·120 words·1 min
Nvim Regex
An Introduction to Lookaround Regular Expression in Neovim/Vim
··614 words·3 mins
Nvim Vim Regex
Notes on Using GCP Logging
·345 words·2 mins
Note GCP Logging Regex