Vim regex backreference

Viewed 48988

I want to do this:

%s/shop_(*)/shop_\1 wp_\1/

Why doesn't shop_(*) match anything?

4 Answers

If you would like to avoid having to escape the capture parentheses and make the regex pattern syntax closer to other implementations (e.g. PCRE), add \v (very magic!) at the start of your pattern (see :help \magic for more info):

:%s/\vshop_(*)/shop_\1 wp_\1/

@Luc if you look here: regex-info, you'll see that vim is behaving correctly. Here's a parallel from sed:

echo "123abc456" | sed 's#^([0-9]*)([abc]*)([456]*)#\3\2\1#'
sed: -e expression #1, char 35: invalid reference \3 on 's' command's RHS

whereas with the "escaped" parentheses, it works:

echo "123abc456" | sed 's#^\([0-9]*\)\([abc]*\)\([456]*\)#\3\2\1#'
456abc123

I hate to see vim maligned - especially when it's behaving correctly.

PS I tried to add this as a comment, but just couldn't get the formatting right.

Related