Ionrock Dot Org

by Eric Larson

My Weblog

Emacs Regexp Search and Replace

This is mainly just a reminder on how to do a search and replace with emacs using regular expressions.

First step is to find what you want to find using the regexp builder (M-x regexp-builder). I'm going to consider this crucial since emacs regex seems to be a little different from other regex engines (ie Python).

Second, once you have your regex, you define a section to capture for later use. Emacs uses parens as literals in regex, so grouping is done via escaping them:

\(http[|s]\)://\(.*\)

This provides two groups, the "http" and the rest after the "://".

Lastly, you do the actual replace-regex and provide the necessary details. To use something you caputured (put in a group) in your replacement,  you either use "\&" when you have no groups, or "\1" where 1 is the group index (like in other regex engines). Here is some code I used it on:

class SomeTest(SeleniumTest):     def __init__(self):         self.t.open('/path/to/test', '')         self.t.pause('500', '')         # ... other commands         self.t.pause('1100', '')         #.... more commands         self.t.pause('1500, '')

What I wanted to do was turn all those pause calls to "self.pause(${time})". Here is what I did in emacs:

M-x replace-regexp RET self.t.pause('\([[:digit:]]+\)', '') RET self.pause('\1') RET

Not very difficult, but when you don't practice that sort of thing it becomes easy to forget.

Posted Fri Aug 21 20:56:26 2009 by Eric Larson
Created using Python, jQuery and Emacs