Next: , Previous: Unconditional Replace, Up: Replace


12.7.2 Regexp Replacement

replace-string replaces exact matches for a single string. The similar command replace-regexp replaces any match for a specified pattern.

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 text being replaced. ‘\d’ in newstring, where d is a digit, stands for whatever matched the d'th parenthesized grouping in regexp. For example,

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

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

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

would perform exactly the opposite replacements. To include a ‘\’ in the text to replace with, you must give ‘\\’.