How do I use a Vim expression to dynamically compute substitution replacement text?
Answer
:s/pattern/\=expression/
Explanation
The \= prefix in the replacement field of :s/// tells Vim to evaluate the right-hand side as a Vim script expression and use the result as the replacement text. This unlocks dynamic substitutions that go beyond simple string replacement — you can perform arithmetic, call functions, or transform matches programmatically.
How it works
\=signals that the replacement is a Vim expression, not a literal stringsubmatch(0)— returns the full matched text as a stringsubmatch(1),submatch(2), etc. — return text captured by parenthesised groups- The expression result is converted to a string and substituted in place of each match
Example
Double every number in a line:
items: 10, price: 5
Run :s/\d\+/\=submatch(0)*2/g:
items: 20, price: 10
Vim matches each sequence of digits, evaluates submatch(0)*2 as an integer expression, and replaces the match with the result.
Tips
- Use
str2nr(submatch(0))for explicit string-to-number conversion on ambiguous inputs toupper(submatch(0))andtolower(submatch(0))transform case via expression- Combine with
:g/pattern/to target only specific lines first, then substitute within them - The global flag
/gapplies the expression to every match on the line, re-evaluating for each - Try
:s/\(\w\+\)/\=len(submatch(1))/gto replace each word with its character count