Tuesday, 6 January 2015

Powerful productivity tip using find and replace in IntelliJ

What better way to kick off this blog than with a super productivity tip!  

In common with probably all developers I use 'find and replace' fairly extensively in my IDE of choice (IntelliJ) but I came across a scenario which taught me me something that really opened my eyes to the power of the Regex expressions in find and replace.  

The following problem confronted me.  I needed to replace all instances of this text:

I should have sma "9000"
with
I should have sma 9000

(Note the removal of the double quotes.)

The problem was that I had this construct scattered hundreds of times through my codebase, each with a different figure inside the quotes.  Obviously I could not just remove all instances of quotes through my code! 

So more generically the problem was to replace:

I should have sma "xxx"
with
I should have sma xxx

I mentioned this to my colleague Peter Lawrey who suggested this approach:

In the find box: I should have sma "(.*)"
In the replace box: I should have sma $1


 
You write a normal regex expression in the 'find', in this case I should have sma ".*", but you surround the part you want to reuse in the 'replace' in round brackets.  You can then access that text in the 'replace' using $1.  

The beauty of IntelliJ is that you can see this in real time by examining an instance of the affected text as you type in the find and replace. The 'find' is highlighted in a white box and the 'replace' is shown as a tooltip.  Makes it super easy to see that your substitution is correct.









If you need more than one of these types of matches in your find and replace no problem.  Each time you use the round brackets just increment the number in the $ as below.

I should have sma "(.*)" and val "(.*)"
with
I should have sma $1 and val $2

2 comments:

  1. I don't think there should be round brackets in the replacement string (unless you want them in the result text, which as per your example you don't) - should be just $1 and $2 there

    ReplyDelete