Version: 4.2.1

9.7 Alternation

You can specify a list of alternate subpatterns by separating them by |. The | separates subpatterns in the nearest enclosing cluster (or in the entire pattern string if there are no enclosing parens).

  > (regexp-match #rx"f(ee|i|o|um)" "a small, final fee")

  ("fi" "i")

  > (regexp-replace* #rx"([yi])s(e[sdr]?|ing|ation)"
                      "analyse an energising organisation"
                      " pulsing with noisy organisms")

  "analyze an energizing organization pulsing with noisy organisms"

Note again that if you wish to use clustering merely to specify a list of alternate subpatterns but do not want the submatch, use (?: instead of (.

  > (regexp-match #rx"f(?:ee|i|o|um)" "fun for all")


An important thing to note about alternation is that the leftmost matching alternate is picked regardless of its length. Thus, if one of the alternates is a prefix of a later alternate, the latter may not have a chance to match.

  > (regexp-match #rx"call|call-with-current-continuation"


To allow the longer alternate to have a shot at matching, place it before the shorter one:

  > (regexp-match #rx"call-with-current-continuation|call"


In any case, an overall match for the entire regexp is always preferred to an overall non-match. In the following, the longer alternate still wins, because its preferred shorter prefix fails to yield an overall match.

  > (regexp-match
     #rx"(?:call|call-with-current-continuation) constrained"
     "call-with-current-continuation constrained")

  ("call-with-current-continuation constrained")