How do I search for the word under the cursor as a substring, not a whole word?
Answer
g* and g#
Explanation
The * and # commands search for the exact whole word under the cursor (with word boundaries \< and \>). Their lowercase counterparts g* and g# do the same search but without word boundaries, treating the word as a substring.
How it works
*— search forward for\<word\>(whole word match only)g*— search forward forword(matches anywhere the substring appears)#— search backward for\<word\>(whole word match only)g#— search backward forword(matches anywhere)
This is especially useful when you want to find all occurrences of a partial identifier, method prefix, or substring that appears inside longer words.
Example
Given this file:
getUser
getUserName
getUserById
setUser
With cursor on User, pressing * only matches User as a complete word. Pressing g* matches User inside getUser, getUserName, getUserById, and setUser.
Tips
- After
g*org#, the search pattern is set without word boundaries — you can usenandNto continue navigating - The search is case-sensitive by default;
:set ignorecaseor adding\cto the pattern affects this - Combine with
cgnto change the next match: afterg*, typecgnthen type the replacement, then.to repeat across all matches