Previous: , Up: Regular Expressions   [Contents][Index]


33.3.3 Regular Expression Functions

These functions operate on regular expressions.

Function: regexp-quote string

This function returns a regular expression whose only exact match is string. Using this regular expression in looking-at will succeed only if the next characters in the buffer are string; using it in a search function will succeed if the text being searched contains string. See Regexp Search.

This allows you to request an exact string match or search when calling a function that wants a regular expression.

(regexp-quote "^The cat$")
     ⇒ "\\^The cat\\$"

One use of regexp-quote is to combine an exact string match with context described as a regular expression. For example, this searches for the string that is the value of string, surrounded by whitespace:

(re-search-forward
 (concat "\\s-" (regexp-quote string) "\\s-"))
Function: regexp-opt strings &optional paren

This function returns an efficient regular expression that will match any of the strings in the list strings. This is useful when you need to make matching or searching as fast as possible—for example, for Font Lock mode17.

If the optional argument paren is non-nil, then the returned regular expression is always enclosed by at least one parentheses-grouping construct. If paren is words, then that construct is additionally surrounded by ‘\<’ and ‘\>’; alternatively, if paren is symbols, then that construct is additionally surrounded by ‘\_<’ and ‘\_>’ (symbols is often appropriate when matching programming-language keywords and the like).

This simplified definition of regexp-opt produces a regular expression which is equivalent to the actual value (but not as efficient):

(defun regexp-opt (strings &optional paren)
  (let ((open-paren (if paren "\\(" ""))
        (close-paren (if paren "\\)" "")))
    (concat open-paren
            (mapconcat 'regexp-quote strings "\\|")
            close-paren)))
Function: regexp-opt-depth regexp

This function returns the total number of grouping constructs (parenthesized expressions) in regexp. This does not include shy groups (see Regexp Backslash).

Function: regexp-opt-charset chars

This function returns a regular expression matching a character in the list of characters chars.

(regexp-opt-charset '(?a ?b ?c ?d ?e))
     ⇒ "[a-e]"

Footnotes

(17)

Note that regexp-opt does not guarantee that its result is absolutely the most efficient form possible. A hand-tuned regular expression can sometimes be slightly more efficient, but is almost never worth the effort.


Previous: , Up: Regular Expressions   [Contents][Index]