Vim regex backreference

I want to do this:

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

Why doesn't shop_(*) match anything?

+46
vim regex
Jul 26 '10 at 21:18
source share
2 answers

Here are a few questions.

  • parens in vim regexen is not meant to be captured - you need to use \( \) for captures.

  • * does not mean what you think. This means β€œ0 or more previous”, so your regular expression means β€œa string containing shop_ followed by 0 + ( and then a literal ) .
    You are looking for . , which in regex means "any character". Comparable to a star as .* , This means "0 or more of any character." You probably need at least one character, so use .\+ ( + Means "1 or more of the previous")

Use this: %s/shop_\(.\+\)/shop_\1 wp_\1/ .

Optionally terminate it with g after the last slash to replace all instances on the same line, not just the first.

+55
Jul 26 '10 at 9:26 a.m.
source share

If I understand correctly, you want %s/shop_\(.*\)/shop_\1 wp_\1/

Exit the copied bracket and use .* To match any number of characters.

(Your search searches for "shop_", followed by any number of opening parentheses, followed by a closing bracket)

+7
Jul 26 2018-10-21T00:
source share



All Articles