Rails on Maui

Programming in Paradise

Using RubyMine/IntelliJ Regexp Search/Replace

RubyMine’s interactive search/replace is awesome. The Regexp feature is especially useful. Not only will it help you edit faster, but it will improve your ability to write RegExp’s in your code. When do you need to use a regexp? Whenever a standard find/replace won’t cut it. For example, if you changing the rspec syntax from one form to another, such as from:

let(:my_subject) { something }
it { expect(my_subject.value).to eq(some_value) }


subject { something }
its(:value) { should eq(some_value) }

The following screencast shows how you can interactively use the Regexp feature to figure out the right regexp to search for as well as the right replacement.

In this example, I’m replacing one rspec syntax with a replacement one.

it \{ expect\(my_subject\.(\w+)\)\.to eq\((.*)\) }

Replace with:

its(:$1) { should eq($2) }

Here’s a few key tips:

  1. Be sure to first check the regexp check-box if you’ll need that.
  2. As you type each character into the search box, observe if you’re increasing your match area to get what you want.
  3. If a character doesn’t match, then try escaping the character. For example, I had to escape the { and ( as those characters have special meaning in the regexp.
  4. Once you get a match with the right groupings for replacement, then put in the $1, $2, etc. into the replacement box to refine your replacement string.
  5. Then hit Opt-P (or Alt-P) to replace.

This is best shown with this 2 minute screencast.