A regular expression (or regexp for short) is a pattern that denotes a class of alternative strings to match. GNU Emacs provides both incremental and nonincremental ways to search for a match for a regexp. The syntax of regular expressions is explained in the following section.
Incremental search for a regexp is done by typing C-M-s
isearch-forward-regexp), by invoking C-s with a
prefix argument (whose value does not matter), or by typing M-r
within a forward incremental search. This command reads a
search string incrementally just like C-s, but it treats the
search string as a regexp rather than looking for an exact match
against the text in the buffer. Each time you add text to the search
string, you make the regexp longer, and the new regexp is searched
for. To search backward for a regexp, use C-M-r
isearch-backward-regexp), C-r with a prefix argument,
or M-r within a backward incremental search.
All of the special key sequences in an ordinary incremental search do similar things in an incremental regexp search. For instance, typing C-s immediately after starting the search retrieves the last incremental search regexp used and searches forward for it. Incremental regexp and non-regexp searches have independent defaults. They also have separate search rings, which you can access with M-p and M-n.
If you type <SPC> in incremental regexp search, it matches any
sequence of whitespace characters, including newlines. If you want to
match just a space, type C-q <SPC>. You can control what a
bare space matches by setting the variable
search-whitespace-regexp to the desired regexp.
In some cases, adding characters to the regexp in an incremental regexp search can make the cursor move back and start again. For example, if you have searched for ‘foo’ and you add ‘\|bar’, the cursor backs up in case the first ‘bar’ precedes the first ‘foo’. See Regexps.
Forward and backward regexp search are not symmetrical, because regexp matching in Emacs always operates forward, starting with the beginning of the regexp. Thus, forward regexp search scans forward, trying a forward match at each possible starting position. Backward regexp search scans backward, trying a forward match at each possible starting position. These search methods are not mirror images.
Nonincremental search for a regexp is done by the functions
re-search-backward. You can
invoke these with M-x, or by way of incremental regexp search
with C-M-s <RET> and C-M-r <RET>.
If you use the incremental regexp search commands with a prefix
argument, they perform ordinary string search, like
isearch-backward. See Incremental Search.