Is it possible to use find and replace on a wildcard string in VIM?

replace, vim, wildcard

Solution

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.

Problem

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.

Original source