simple regex - between double quotations replace space with underscore and make all letters lowercase

regex, vim

Solution

A generic approach:

:%s/\(<string name="\)\(\u\)\([^" ]\+\) \([^" ]\+\)/\1\l\2\e\3_\4/

This replaces every string @name that

- starts with an upper case character (`\u`) and

- consists of two space-separated words (`\([^" ]\+\) \([^" ]\+\)`) and

- replaces it with the corresponding lower-case character (`\l\2\e`).

- It also replaces the space with an underscore.

To make everything in @name lower-case, this could be simplified:

:%s/\(<string name="\)\([^" ]\+\) \([^" ]\+\)/\1\l\2_\3_\e/

To get rid of multiple spaces, do two steps. First, make the attribute value lower-case:

:%s/\(<string name="\)\([^"]\+\)/\1\l\2\e/

then, replace every space in the attribute value with an underscore

:%s/\(<string name="[^"]*\)\@<= /_/g

Note that the `\@<=` is vim's way of expressing a positive look-behind assertion.

Problem

Could you help me with a regex to change lines like ``` <string name="Final time">Final time</string> <string name="After extra time">After extra time</string> ``` to lines ``` <string name="final_time">Final time</string> <string name="after_extra_time">After extra time</string> ``` So between double quotations replace space with underscore and make all letters lowercase. I will use this regex with search/replace in VIM.

Original source