← Back to Archives

Emacs Regex

blogging

(as is the case with many of my blog posts, this one is for me... so you might not find it all that interesting)

In writing my very long post yesterday about OVL incident reports, I had to do a series of replacements. For example, I had a set of text like this:

[12345] [21345] [13245] [12435] ...

and I needed each line to look like this (a Markdown anchor):

[12345]: http://foo.bar/do?id=12345 ...

Obviously, I could do this by hand, but that would be silly and hurt my hands. Of course, my thoughts instantly turned to Emacs' replace-regexp command which will run search on a regular expression and replace that text with text of your choosing.

In this case, I hit M-x replace-regexp and entered this as the search string:

[([0-9]{5})]

Which says, "look for any series of 5 numbers within square brackets, and save the 5 numbers for the replacement operation". After hitting return, I construct the replace text like so:

[\1]: http://foo.bar/do?id=\1

The \1 tells Emacs to replace this string with what it found in the search part of the operation between parentheses (although note that the parentheses have to be escaped in the search target above: \( and \)).

You can use the parenthesis trick in replace-regexp to do all sorts of neat stuff... check the Emacs manual for the specific syntax for Emacs regular expressions.