How do I search for a second pattern relative to where the first one matched?
Answer
/pattern1/;/pattern2/
Explanation
Vim's search offsets allow chaining two patterns together with a semicolon. /pattern1/;/pattern2/ first jumps to pattern1, then — from that position — immediately searches forward for pattern2. This lets you navigate to something that only makes sense relative to another match, without writing a single complex regex.
How it works
/pattern1/— normal forward search; jumps to the first match;— after jumping topattern1, search forward from there/pattern2/— the second search, executed from the position ofpattern1's match- The cursor lands on
pattern2 - You can chain more than two:
/a/;/b/;/c/findscafterbaftera - Works with
?for backward searches too
Example
In a large config file, jump to the [database] section header and then find the first host = line within it:
/\[database\]/;/host =/
This is more precise than /host =/ alone, which might land on a host = in the wrong section.
Tips
- Use
nandNafter a chained search to repeat the compound jump - The semicolon offset is especially powerful with
%sranges — combine it with:gfor complex multi-pattern edits - In very magic mode (
\v), the syntax is the same:/\v\[database\]/;/host =/ - The first pattern can have its own offset too:
/pattern1/e;/pattern2/lands after the end ofpattern1before searching forpattern2