I want to match a pattern, replace part of the pattern, and use a variable within the pattern as part of the replacement string.
Is this correct?
/s/^((\\s
I presume you want to replace it in vi
Replace all occurrences
:s/^\(\s\+\)private function __construct()/\1def __init__/g
Replace first
:s/^\(\s\+\)private function __construct()/\1def __init__/
Few suggestions to your pattern
/
is used in vi
for search , use :
(
)
in vi\i
where i is xth capture group like \1
\2
to back reference grouped patterns in replacement\s
can not be used in replacement text use ' '
instead/g
if you want to replace all occurrenceshttp://vimregex.com should help you get started.
I don't think anyone really understood the question. Basically, the way I'm doing this is as follows:
"If you want to search for a replacement pattern, pattern a, and replace it with a replacement string, pattern i, only if it starts with a pattern, pattern b, then you need to include pattern b in the replacement string, like this: :/(pattern b)(pattern a)/(pattern b)(i)/g".
It's a little wordy but worth reading.
In the past, I'm sure that someone has thought, "It could save a lot of resources to not actually replace pattern b
with pattern b
. It's redundant to do so." Maybe it happens automatically. I haven't found a built-in method in vi or any other program to do that. I'm sure I could write a script to do it, though.
This is called a backreference, and you use \i
to refer to the i'th captured group from the pattern.
So for the pattern ^((\s+)private\sfunction\s__construct\(\))
, the replacement is \2def __init__
.