IntelliJ Find and Replace with regular expressions

Regular expressions are not my forte, but never the less very useful. Recently I faced this fictional code snippet:

var a = someFunc(b, c);
//.....
var d = someFunc(b, d);

Almost a gazillion of calls to someFunc needed to be replaced with otherFunc. Cue big gasp! As always, IntelliJ is your go-to companion you always can rely on.

I already noticed the regex checkbox in the Find/Replace dialog. Now it’s time to put this thing into practice. And it just works great.

In the find input, you just enter any regular expression, in my case someFunc\((.*)\). In plain English, I’m looking for:

  1. the literal text someFunc;
  2. followed by a left parenthesis. Parenthesis’s are used for grouping of characters, hence the escaping with a backslash;
  3. Next part is (.*), which means ‘take any characters and consider it as 1 group’;
  4. Ending with the closing parenthesis.

Now the group can be re-used in the replace input. So for me it was otherFunc\($1\). Again escaping the parenthesis and between them, the group as defined in the regular expression in the input. So for the first statement in the snippet above, $1 would be b, c.

Once again, it’s proven that regular expressions are worthwhile learning!


202 Words

2020-05-10 12:16 +0200