使用 vim 搜索功能,是否可以避免在注释 block /行上进行匹配。
例如,我想在此 python 代码中匹配“图像”,但仅在代码中,而不是在注释中:
# Export the image
if export_images and i + j % 1000 == 0:
export_image(img_mask, "images/image{}.png".format(image_id))
image_id += 1
使用正则表达式我会做这样的事情:/^[^#].*(image).*/gm
但在 vim 中似乎不起作用。
最佳答案
你可以使用
/^[^#].*\zsimage\ze
\zs
and \ze
分别表示比赛的开始和结束。
- setting the start and end of the match:
\zs \ze
请注意,这不会匹配一行中的多个“图像”,只会匹配最后一个。
此外,也许“否定前瞻”会比开头的否定字符类更好:
/^#\@!.*\zsimage\ze
^^^^
#\@!
等于(?!#)
在 Python 中。
而且因为在 Vim 中后视是非固定宽度的 ( like (?<=pattern)
in Perl, but Vim allows non-fixed-width patterns ),你可以匹配字符序列 image 的所有匹配项
/\(^#\@!.*\)\@<=image
最后跳过缩进注释行上的匹配图像,您只需要匹配可选(零个或多个)空白符号( s) 在行首:
\(^\(\s*#\)\@!.*\)\@<=image
^^^^^^^^^^^
这\(\s*#\)\@!
相当于 Python (?!\s*#)
(如果后面没有后跟零个或多个空格后跟 #
则匹配)。
关于python - Vim 搜索 : avoid matches within comments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35323148/