Regex Search and Replace in Emacs

Tony Aldon has a short video on a couple of alternate ways to do regex search and replace in Emacs. The straightforward way to do that is to use query-replace-regexp (Ctrl+Meta+%) but you can do the same operation in steps by first doing isearch-forward-regexp (Ctrl+Meta+s) to make sure you’re finding the right search object and then calling query-replace-regexp to specify the replacement. That’s not as wasteful as it seems because it will remember the search string from the isearch-forward-regexp and you need only specify the substitution.

Aldon gives an example of this in operation so you can see exactly how it works. Take a look at the video to see the details.

The second method is essentially the same except that it uses the package visual-regexp to get immediate feedback on what the regular expression will match as you type it. That can be pretty handy if Emacs regular expressions are your second choice for regex work and you don’t use them all the time. Again, take a look at the video to see the package in action.

Most of the time you’re probably better off to just use query-replace-regexp but if you’re unsure of the regex, the two step process can make sense. The first method uses functions that are all built-in so it’s always available. If you want to see what’s going to be matched as you enter the regex, the visual-regexp package may be for you.

The video is only 8 minutes so it should be easy to fit in.

This entry was posted in General and tagged . Bookmark the permalink.