ILikeTacos
ILikeTacos

Reputation: 18696

How to access regex matches in vim using search/replace?

Sample:

function foobar($arg1 = null, $arg2 = null) {
    $_a = $arg1;
    $_b = $arg2;
}

I want to write a search and replace regex in vim that does this:

function foobar($arg1 = null, $arg2 = null) {
   $_a = (!$arg1) ? $arg1 : 1;
   $_b = (!$arg2) ? $arg2 : 1;
 }

This is what I've tried so far:

  1. Using the . command to repeat my last action in vim, but it only appends : 1; to the lines
  2. I've written dozens of variations of this regex, but can't get it to work as expected: %s/\$_a\t=\t*/(!\$arg1)\t\?\t\2\t\:\t1/g
  3. Replace the lines manually, but it goes without saying that I've to do this over huge number of files.

Basically what I want to do is to write a regex that matches $arg1 and then enclose the match with the ternary operator, but I haven't been able to access the regex matches in vim.

Any help will be greatly appreciated!

(it doesn't have to be done in vim, I'm open to suggestions like using perl)

Thanks!!

Upvotes: 0

Views: 240

Answers (2)

Alan Gómez
Alan Gómez

Reputation: 378

A more general way to do that:

:%s/= \(.*\);/= (!\1) ? \1 : 1;

This replace whatever is $arg1 not just $arg plus any number.

Upvotes: 0

falsetru
falsetru

Reputation: 369454

Try following command:

:%s/\(\$arg[0-9]\);/(!\1) ? \1 : 1;

Above command replace $arg1; with (!$arg1) ? $arg1 : 1;

Upvotes: 1

Related Questions