Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim regex backreference

Tags:

regex

vim

I want to do this:

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

Why doesn't shop_(*) match anything?

like image 471
nnyby Avatar asked Jul 26 '10 21:07

nnyby


People also ask

What is Backreference regex?

A backreference in a regular expression identifies a previously matched group and looks for exactly the same text again. A simple example of the use of backreferences is when you wish to look for adjacent, repeated words in some text.

How to search regex in Vim?

In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.

Does vim support regex?

Vim has several regex modes, one of which is very magic that's very similar to traditional regex. Just put \v in the front and you won't have to escape as much.


2 Answers

There's several issues here.

  1. parens in vim regexen are not for capturing -- you need to use \( \) for captures.

  2. * doesn't mean what you think. It means "0 or more of the previous", so your regex means "a string that contains shop_ followed by 0+ ( and then a literal ).
    You're looking for ., which in regex means "any character". Put together with a star as .* it means "0 or more of any character". You probably want at least one character, so use .\+ (+ means "1 or more of the previous")

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

Optionally end it with g after the final slash to replace for all instances on one line rather than just the first.

like image 89
Daenyth Avatar answered Sep 29 '22 09:09

Daenyth


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

Escape the capturing parenthesis and use .* to match any number of any character.

(Your search is searching for "shop_" followed by any number of opening parentheses followed by a closing parenthesis)

like image 29
Stephen Avatar answered Sep 29 '22 10:09

Stephen