How do I search only a sub-part of a larger pattern using \zs and \ze?
Answer
/foo\zsbar\zebaz<CR>
Explanation
Sometimes you need Vim to match a long structural pattern but only treat one piece of it as the actual match. \zs and \ze solve this cleanly: they redefine where the match starts and ends without changing the surrounding context checks. This is especially useful in advanced search-and-replace workflows where you want precise targeting without capturing groups and backreference noise.
How it works
/starts a forward searchfoois required context before the real target\zssets the start of the reported match at this pointbaris the part Vim treats as the match\zesets the end of the reported matchbazis required trailing context after the match
Vim still requires the whole foobarbaz structure, but only bar is considered the matched text.
Example
Given:
foobarbaz
fooquxbaz
foobaz
Search with:
/foo\zsbar\zebaz
Only the bar inside foobarbaz is matched. The other lines are skipped because they do not satisfy both required contexts.
Tips
\zsand\zework with:substitute, so you can replace just the inner segment while anchoring on rich context.- Prefer this over broad groups when you want concise patterns that are easier to read during iterative edits.