Tuesday, March 15, 2011

Emacs back references in replace-regex.

From http://www.gnu.org/software/emacs/manual/html_node/emacs/Regexp-Replace.html

In replace-regexp, the newstring need not be constant: it can refer to all or part of what is matched by the regexp. ‘\&’ in newstring stands for the entire match being replaced. ‘\d’ in newstring, where d is a digit, stands for whatever matched the dth parenthesized grouping in regexp. (This is called a “back reference.”) ‘\#’ refers to the count of replacements already made in this command, as a decimal number. In the first replacement, ‘\#’ stands for ‘0’; in the second, for ‘1’; and so on. For example,

M-x replace-regexp <RET> c[ad]+r <RET> \&-safe <RET>

replaces (for example) ‘cadr’ with ‘cadr-safe’ and ‘cddr’ with ‘cddr-safe’.