lookarounds positive negative lookbehind lookahead

眉间皱痕 提交于 2019-12-01 16:26:40

For any newcomers, I'll copy the contents of this link here for the future:

http://ssiaf.blogspot.ru/2009/07/negative-lookbehind-in-vim.html

/\(Start\)\@<!Date

This will match the 'Date' in 'EndDate' and 'YesterdaysDate' but will not match 'StartDate'

/Start\(Date\)\@!

will match the 'Start' in 'Starting but not in 'StartDate'

/Start\(Date\)\@=

will match the 'Start' in 'StartDate' but not in 'Starting

/\(Start\)\@<=Date

will match the 'Date' in 'StartDate' but not in 'EndDate' and 'YesterdaysDate'

I want to expand on the excellent answer from @briansrls. I was looking for a more robust solution that could handle multi-word phrases, wildcards (for potential gaps between phrases) and alternatives (i.e., patterns):

Without wildcards:

  Positive Lookahead:  \(find this\)\(followed by this\|or that\)\@=
  Negative Lookahead:  \(find this\)\(not followed by this\|or that\)\@!
  Positive Lookbehind: \(preceded by this\|or that\)\@<=\(find this\)
  Negative Lookbehind: \(not preceded by this\|or that\)\@<!\(find this\)

With wildcards:

  Positive lookahead:  \(find this\)\(.*\(eventually followed by this\|or that\)\)\@=
  Negative lookahead:  \(find this\)\(.*\(not eventually followed by this:\|or that\)\)\@!
  Positive lookbehind: \(\(eventually preceded by this\|or that\).*\)\@<=\(find this\) 
  Negative lookbehind: \(\(not eventually preceded by this\|or that\).*\)\@<!\(find this\)

Note: For the wildcard versions, the extra parentheses are required so that the wildcard is excluded from the alternatives group, but is included in the lookaround group. This prevents duplicating the wildcards for every alternative. One could also use \zs & \ze to avoid the extra parentheses, but I find this method slightly more intuitive.

For more information:

Update: It appears that \zs & \ze are not yet implemented in VsVim as of this time.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!