Vim searching: avoid matches within comments

You can use

/^[^#].*\zsimage\ze

The \zs and \ze signalize the start and end of a match respectively.

  • setting the start and end of the match: \zs \ze

Note that this will not match several "image"s on a line, just the last one.

Also, perhaps, a "negative lookahead" would be better than a negated character class at the beginning:

/^#\@!.*\zsimage\ze
  ^^^^

The #\@! is equal to (?!#) in Python.

And since look-behinds are non-fixed-width in Vim (like (?<=pattern) in Perl, but Vim allows non-fixed-width patterns), you can match all occurrences of the character sequence image with

/\(^#\@!.*\)\@<=image

And to finally skip matching image on an indented comment line, you just need to match optional (zero or more) whitespace symbol(s) at the beginning of the line:

\(^\(\s*#\)\@!.*\)\@<=image
   ^^^^^^^^^^^   

This \(\s*#\)\@! is equivalent to Python (?!\s*#) (match if not followed by zero or more whitespace followed with a #).


This mailing list post suggest using folds:

To search only in open folds (unfolded text):

:set fdo-=search

To fold # comments, adapting on this Vi and Vim post (where an autocmd for Python files is given):

set foldmethod=expr foldexpr=getline(v:lnum)=~'^\s*#'

However, folding by default works only on multiple lines. You need to enable folding of a single line, for single-line comments to be excluded:

set fml=0

After folding everything (zM, since I did not have anything else to be folded), a search for /image does not match anything in the comments.

Tags:

Python

Vim

Regex