0

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

This one worked:

%s/\(armv7_format_strings.*\) = {\(.*\), \(.*\)};/\1[0] = \2;\r\1[1] = \3;\r/gc
1

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")/

Overview

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.

Glory of Details

  • %s:^\(\s*armv7_format_strings.*\) = {\([^}]*\)};/\={expr}/ - Capture the {lhs} and {rhs}
  • use an sub-replace-expression, \={expr}, to use {expr} as the replacement.
  • submatch(1) is the {lhs} aka \1 in normal regex speak
  • submatch(2) is the {rhs} aka \2 in normal regex speak
  • split(submatch(2), '\s*,\s*') - split the {rhs} by ,. Yields are parameters as a List
  • map({lst}, {expr}) - map() will update the list by evaluating {expr}
  • use submatch(1)."[".v:key."] = ".v:val.";" as our expression, {expr}
  • v:val will the each single item in the List
  • v:key will the the index of the List
  • join({lst}, "\r") will join the list together as new lines

For more help

:h sub-replace-expression
:h join(
:h map(
:h split(
:h submatch(
0

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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