I want to replace all of the occurrences of
armv7_format_strings<any_string> = {<str1>, <str2>};
by
armv7_format_strings<any_string>[0] = <str1> ;
armv7_format_strings<any_string>[1] = <str2> ;
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityI want to replace all of the occurrences of
armv7_format_strings<any_string> = {<str1>, <str2>};
by
armv7_format_strings<any_string>[0] = <str1> ;
armv7_format_strings<any_string>[1] = <str2> ;
This one worked:
%s/\(armv7_format_strings.*\) = {\(.*\), \(.*\)};/\1[0] = \2;\r\1[1] = \3;\r/gc
You can use a substation with a sub-replace-expression.
:%s/^\(\s*armv7_format_strings.*\) = {\([^}]*\)};/\=join(map(split(submatch(2), '\s*,\s*'), 'submatch(1)."[".v:key."] = ".v:val.";"'),"\r")/
Basically this captures the left hand side ({lhs}
) and the right hand side ({rhs}
) separately. Then splits the {rhs}
by ,
(aka parameter) and concatenates the {lhs}
to each new parameter. Finish the substitution by joining each new line together with a new line, "\r"
.
Note: this will fail for tricky strings, e.g. "foo,bar"
as this method just assumes no ,
or }
inside of strings.
%s:^\(\s*armv7_format_strings.*\) = {\([^}]*\)};/\={expr}/
- Capture the {lhs}
and {rhs}
\={expr}
, to use {expr}
as the replacement.submatch(1)
is the {lhs}
aka \1
in normal regex speaksubmatch(2)
is the {rhs}
aka \2
in normal regex speaksplit(submatch(2), '\s*,\s*')
- split the {rhs}
by ,
. Yields are parameters as a Listmap({lst}, {expr})
- map()
will update the list by evaluating {expr}
submatch(1)."[".v:key."] = ".v:val.";"
as our expression, {expr}
v:val
will the each single item in the Listv:key
will the the index of the Listjoin({lst}, "\r")
will join the list together as new lines:h sub-replace-expression
:h join(
:h map(
:h split(
:h submatch(
While I'd use the regex swap you could also do it with a macro.
qq^vt=h"ayf{lvt,"byf,lvt}"cydd<CTRL_r>a[0] = <CTRL_r>b;<Enter><CTRL_r>a[1] = <CTRL_r>c;q
Its basically the same as the regex. Yank the left side of the equals into register a, and the two strings in the array into registers b and c. Delete the line, and paste RegA[0] = RegB;\nRegA[1] = RegC;