49

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.

3 Answers 3

70

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.

4
  • is there a difference between the \w\+ and .*?
    – dwcanillas
    Apr 26, 2012 at 15:48
  • 9
    \w\+ matches one or more in this set: a-zA-Z0-9_ and .* matches zero or more of anything.
    – gpojd
    Apr 26, 2012 at 15:51
  • Just tried it on the code I wanted to search and replace on, and it worked like a charm. thanks again!
    – dwcanillas
    Apr 26, 2012 at 16:02
  • 1
    If you want to match a fixed number of occurrences you can use \w\{n,m} or \w\{,m} to match up to a max number of occurrences Aug 1, 2018 at 19:19
9

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/
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.