1

After reading about Vim regexs, my head hurts.

I'd like to change all words ending in _bar into words starting with bar_.

So for example:

var variable_foo = "foo",
    more_foo = "foo";

would become:

var foo_variable = "foo",
    foo_more = "foo"; // New variable names

I know the answer will involve :%s/<something>/<something else>/g.

The answer should be robust to coding-style word boundaries like this:

(inside_parens_foo)

changes to

(foo_inside_parens)
LondonRob
  • 73,083
  • 37
  • 144
  • 201
  • Use `:%s/\(\w\+\)_\(\w\+\)/\2_\1/g` as suggested by [Peter Rincker](http://stackoverflow.com/users/438329/peter-rincker). – devnull Apr 22 '14 at 19:00

1 Answers1

4

As @devnull stated you need to use back-references:

:%s/\(\w\+\)_\(\w\+\)/\2_\1/g

Use \w to capture word like characters, [0-9A-Za-z_]. I would also recommend using the c flag to confirm changes.

As @benjifisher stated using the \v to turn on "very magic" will cut down the line noise:

:%s/\v(\w+)_(\w+)/\2_\1/g

For more help see:

:h :s_c
:h \1
:h /\w
:h /\+
:h /\v
Peter Rincker
  • 43,539
  • 9
  • 74
  • 101
  • This is a fantastic answer. Would you be able to add a little about what the `+` symbol does? (Or how to find help on it?) Then it will be complete! – LondonRob Apr 23 '14 at 11:05
  • The `+` is a regex quantifier. It means one or more times. I would suggest you look at `:h pattern` for vim regex information. I suggest you look for some regex tutorials or at the very least this [SO post](http://stackoverflow.com/a/2759417/438329). – Peter Rincker Apr 23 '14 at 13:20