Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find replace using regex groups in vim

Tags:

regex

vim

I'm replacing all the inline gist snippets w/ a div to load them in a non blocking way. To modify all the legacy articles that have the following

<script src='https://gist.github.com/1234.js?file=gistfile1.sh'></script>

I need to replace it with the following instead

<div data-gist=1234><a href='http://gist.github.com/1234'>gistfile1.m</a></div>

So far what I'm trying (vim newb here) -doesn't seem to work

:%s/<script src='https:\/\/gist.github.com\/(d+).js?file=gistfile1.sh'><\/script>/<div data-gist={1}><a href='http://gist.github.com/{1}'>gistfile1.m</a></div>//g
like image 353
Toran Billups Avatar asked Jun 17 '12 17:06

Toran Billups


People also ask

How do I match a group in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

What regex does Vim use?

vim which translates from PCRE (Perl-compatible regular expressions) to Vim's regex syntax. This will make it more likely for regexes from other environments to work, because PCRE have become the de facto industry standard: e.g. Java's java.

How do I match a pattern 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.


1 Answers

I got it to work with this:

:%s!<script src='https://gist.github.com/\(\d\+\).js?file=gistfile1.sh'></script>!<div data-gist=\1><a href='http://gist.github.com/\1'>gistfile1.m</a></div>!g 

Couple things to note:

  1. I used ! instead of / as seperator to avoid having to escape path slashes
  2. You need to escape (, d, +, and ) in your attempt.
  3. You had extra / at the very end.
  4. To insert the match group, use \1 instead of {1}
like image 81
Tim Avatar answered Sep 19 '22 14:09

Tim