Vim Search: Avoid Matching in Comments

Using the vim search capabilities, you can avoid a match in the comment block / line.

As an example, I would like to combine into an 'image' in this python code, but only in the code and not in the comment:

# Export the image
if export_images and i + j % 1000 == 0:
export_image(img_mask, "images/image{}.png".format(image_id))
image_id += 1

Using regular expressions, I would do something like this: /^[^#].*(image).*/gm But this does not work in vim.

+6
source share
3 answers

you can use

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

\zsand\ze signal the start and end of the match, respectively.

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

Note that this will not match multiple “images” per line, only the last.

, , " " , :

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

Python #\@! (?!#).

, look-behinds Vim ( (?<=pattern) Perl, Vim -fixed-width patterns),

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

, , , ( ) :

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

\(\s*#\)\@! Python (?!\s*#) (, , #).

+6

( ):

:set fdo-=search

#, Vi Vim ( autocmd Python):

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

. , :

set fml=0

(zM, ), /image - .

+5

( , , ):

/\v%(^.{-}\/\/.{-})@<!<%(this|that|self|other)>

:

:

some.this = 'hello'
  some.this = 'hello' + this.someother;
 some.this = 'hello' + this.someother; // this is a comment, and this is another

The above expression will match all this/ thatwords except those that are inside the comment (or any other //-prefixed comments , for that matter).

(Note: all links point to reference documentationvim-7.0 , which should (and works in my own testing) also work in the latest versions of vim and nvim at the time of writing)

0
source

Source: https://habr.com/ru/post/1628180/


All Articles