Reputation: 3651
For example, I have a bunch of values with a common prefix and postfix, such as:
fooVal1Bar;
fooVal2Bar;
fooVal3Bar;
In this case, all variable names begin and end with foo
and end with Bar
. I want to use a find and replace using the random variable names found between foo
and Bar
. Say I already have variables Val1
, Val2
, Val3
, and Val1Old
, Val2Old
, and Val3Old
Defined. I would do a find a replace, something along the lines of:
:%s/foo<AnyString>Bar/foo<AnyString>Bar = <AnyString> + <AnyString>Old
This would result in:
fooVal1Bar = Val1 + Val1Old;
fooVal2Bar = Val2 + Val2Old;
fooVal3Bar = Val3 + Val3Old;
I hope it's clear what I want to do, I couldn't find anything in vim help or online about replacing with wildcard strings. The most I could find was about searching for wildcard strings.
Upvotes: 50
Views: 52182
Reputation: 23065
You need to capture what you want to save. Try something like this:
%s/\(foo\(\w\+\)Bar\);/\1 = \2 \2Old/
Or you can clean it up a little bit with \v
magic:
%s/\v(foo(\w+)Bar);/\1 = \2 \2Old/
Upvotes: 9
Reputation: 1129
Replace string with wildcard
:%s/foo.*Bar/hello_world/gc
Here, .*
handles wildcoard follows regex more info on regex quantifiers
. - Any character except line break
* - Zero or more times
Upvotes: 5
Reputation: 40499
I believe you want
:%s/foo\(\w\+\)Bar/& = \1 + \1\Old/
explanation:
\w\+
finds one or more occurences of a character. The preceeding foo and following Bar ensure that these matched characters are just between a foo
and a Bar
.
\(...\)
stores this characters so that they can be used in the replace part of the substitution.
&
copies what was matched
\1
is the string captured in the \(....\)
part.
Upvotes: 70