Sams Teach Yourself Emacs in 24 Hours

ContentsIndex

Hour 9: Regular Expressions

Previous HourNext Hour

Sections in this Hour:

 

Regular Expression Search-and-Replace


The function query-replace-regexp is the regular expression equivalent to query-replace described in Hour 7. The difference is that you can use regular expressions in the search string, and you can refer to some part of the text matched in the search string.

To match text for reference in the replacement string, you must group the given text with \(...\). To use the content of a given match, simply count the number of opening braces, and use that number after a backslash. For example, you can use \1, \2, \3, and so on. You do not need to use all such references, as some of them simply might be for handling precedence.

Match Text in a Regular Expression Search String

This task shows you how to match text in the regular expression search string, which you can use in the replacement string. Follow these steps:

1. Press M-x, type query-replace-regexp, and press Enter.

2. Emacs asks for a regular expression to search for. Type ^Dear *\(Mr\|Miss\)\. *\(.*\)$. This, for example, matches the string Dear Mr. Jesper Peterson. Press Enter.

3. Emacs now asks for replacement text. Type Hi \2, long time no see. Finally press Enter to search the query replace operation.

Note that in the preceding, the first set of parentheses only served to group the alternative and therefore is not referenced in the replacement text.

Sams Teach Yourself Emacs in 24 Hours

ContentsIndex

Hour 9: Regular Expressions

Previous HourNext Hour

Sections in this Hour: