vimtricks.wiki Concise Vim tricks, one at a time.

How do I search for a pattern only within specific columns of a line?

Answer

/\%>5c\%<20cpattern

Explanation

How it works

Vim's search patterns support column position constraints using the \%c family of atoms. These let you restrict where on a line a match can occur:

  • \%Nc matches at exactly column N
  • \%>Nc matches after column N (columns N+1 and beyond)
  • \%<Nc matches before column N (columns 1 through N-1)

Combine two constraints to create a column range. For example, \%>5c\%<20c restricts the match to columns 6 through 19.

There are also virtual column variants (\%v) that account for tabs being expanded to their display width:

  • \%Nv matches at virtual column N
  • \%>Nv and \%<Nv work the same way with virtual columns

This feature already exists for lines too (as in \%>10l\%<20l for line ranges), and columns work the same way.

Example

Suppose you have a CSV file and want to find patterns only in the first field (roughly the first 15 characters):

/\%<16cERROR

This finds ERROR only when it appears in the first 15 columns, ignoring matches in later fields.

Another use case is finding long lines. To highlight any character beyond column 80:

/\%>80v.\+

This matches all text past column 80, which is useful for enforcing line length limits.

You can also use this in substitutions to modify text in a specific column range:

:%s/\%>10c\%<20c\d\+/XXX/g

This replaces numbers that appear between columns 11 and 19, leaving numbers in other columns untouched. Column-constrained searches are a unique Vim feature not found in most other regex engines.

Next

How do you yank a single word into a named register?