Search & Replace with Expressions


When the {string} starts with "\=" it is evaluated as an expression, which provides additional flexibility.

To demonstrate a simple example of substitution with an expression, let's repeat the example from the previous section with an expression.

As before we will start with the following buffer:

Initial Conditions
Madison·Angelica·Mcbride
Sarah·Kristine·Ryan
Daniel·Justin·Baker
Meagan·Linda·Harvey
Abigail·Julia·Lewis
Megan·Jacqueline·Morris
Preston·Daniel·Moore
Sheryl·Michelle·Hill
COMMANDTop1:1
:%s/^\(\w\+\)\s\(\w\)\w\+\s\(\w\+\)$//n

and use the same search pattern.

The replacement string can contain a complex expression, containing. For example, in this example we will combine string concatenation with the submatch function to replicate the previous result:

\=submatch(3).', '.submatch(1).' '.submatch(2)

Which, when executed, yields the expected result:

Execute the subsitution
Mcbride,·Madison·A
Ryan,·Sarah·K
Baker,·Daniel·J
Harvey,·Meagan·L
Lewis,·Abigail·J
Morris,·Megan·J
Moore,·Preston·D
Hill,·Sheryl·M
NORMAL89%8:1
8 substitutions on 8 lines

This example was intended to show a simple example of how to implement a substitution that leverages expressions, rather than demonstrate the additional flexibility that expressions offer.