Skip to content

How do I use regexps (regular expressions) in Emacs?

See Regexp Backslash in The GNU Emacs Manual.

The or operator is ‘\|’, not ‘|’, and the grouping operators are ‘\(’ and ‘\)’. Also, the string syntax for a backslash is ‘\\’. To specify a regular expression like ‘xxx\(foo\|bar\)’ in a Lisp string, use ‘xxx\\(foo\\|bar\\)’.

Note the doubled backslashes!

  • Unlike in Unix grep, sed, etc., a complement character set (‘[^...]’) can match a newline character (LFD a.k.a. C-j a.k.a. ‘\n’), unless newline is mentioned as one of the characters not to match.
  • The character syntax regexps (e.g., ‘\sw’) are not meaningful inside character set regexps (e.g., ‘[aeiou]’). (This is actually typical for regexp syntax.)