Emacs: transform regexp replacement string

December 11, 2025

When doing a replace-regexp operation in emacs, you can specify a function to process the replacement, using \, as prefix.

Very convenient to transform copy-pasted text into enums. Consider the text below I copied from the WASM spec:

0 custom section
1 type section
2 import section
3 function section
4 table section
5 memory section
6 global section
7 export section
8 start section
9 element section
10 code section
11 data section

From it, I want to make entries of the form SectionName = 0xID.

M-x replace-regexp RET
\([0-9]+\) \(.*\) section RET
\,(capitalize \2) = \,(format "0x%02x" (string-to-number \1)), RET

The first capture group is for the digit(s), the second for the section name. On replace, capitalize the name and transform the digits into a number in hex format.

And here's the result:

Custom = 0x00,
Type = 0x01,
Import = 0x02,
Function = 0x03,
Table = 0x04,
Memory = 0x05,
Global = 0x06,
Export = 0x07,
Start = 0x08,
Element = 0x09,
Code = 0x0a,
Data = 0x0b,