Using RubyMine/IntelliJ Regexp Search/Replace

productivityJanuary 25, 2014Dotby Justin Gordon

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) }

to

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.

Closing Remark

Could your team use some help with topics like this and others covered by ShakaCode's blog and open source? We specialize in optimizing Rails applications, especially those with advanced JavaScript frontends, like React. We can also help you optimize your CI processes with lower costs and faster, more reliable tests. Scraping web data and lowering infrastructure costs are two other areas of specialization. Feel free to reach out to ShakaCode's CEO, Justin Gordon, at justin@shakacode.com or schedule an appointment to discuss how ShakaCode can help your project!
Are you looking for a software development partner who can
develop modern, high-performance web apps and sites?
See what we've doneArrow right