Last Updated: February 25, 2016
· chewxy

Sublime Text supports regex backreferences for search and replace

Say you have a lot of code that looks like this:


That is to say you have a lot of the code with the same pattern (typically function calls).

Now you changed the function definition from taking 1 argument to taking more than 1 argument,

func fn(arg1 int) {} ----> func (arg1 int, arg2 int) {}

And say you have many fn() calls.

What you can do is to use SublimeText's regex backref support to search and replace (ctrl+H is default).

Simply do this in your search field:


And use this in your replace field:

fn(\1, arg2)

You should get something like this:

fn(xExp, arg2)
fn(yExp, arg2)
fn(zExp, arg2)
fn(aStmt, arg2)
fn(bStmt, arg2)

I tried this on a whim not 5 minutes ago and discovered to my delight that it works. Of course, (.+) is a very very bad practice, and you should use a pattern that is as specific as possible. You can also do multiple backref with \1, \2 etc. I find that this helps immensely with larger refactors

I was quite pleasantly surprised with what ST can do (of course if you want to do more complex replace, just use emacs and write a quick and dirty script)