vimtricks.wiki Concise Vim tricks, one at a time.

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 for word (matches anywhere the substring appears)
  • # — search backward for \<word\> (whole word match only)
  • g# — search backward for word (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* or g#, the search pattern is set without word boundaries — you can use n and N to continue navigating
  • The search is case-sensitive by default; :set ignorecase or adding \c to the pattern affects this
  • Combine with cgn to change the next match: after g*, type cgn then type the replacement, then . to repeat across all matches

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?