Function: match-string
match-string is a byte-compiled function defined in subr.el.gz.
Signature
(match-string NUM &optional STRING)
Documentation
Return the string of text matched by the previous search or regexp operation.
NUM specifies the number of the parenthesized sub-expression in the last regexp whose match to return. Zero means return the text matched by the entire regexp or the whole string.
The return value is nil if NUMth pair didn't match anything, or if there were fewer than NUM sub-expressions in the regexp used in the search.
STRING should be given if the last search was by string-match
on STRING. If STRING is nil, the current buffer should be the
same buffer as the one in which the search/match was performed.
Note that many functions in Emacs modify the match data, so this
function should be called "close" to the function that did the
regexp search. In particular, saying (for instance)
M-: (looking-at "[0-9]") RET followed by M-: (match-string 0) RET
interactively is seldom meaningful, since the Emacs command loop
may modify the match data.
Other relevant functions are documented in the regexp group.
Probably introduced at or before Emacs version 19.29.
Shortdoc
;; regexp
(and (string-match "^\\([fo]+\\)b" "foobar") (match-string 0 "foobar"))
=> "foob"
Source Code
;; Defined in /usr/src/emacs/lisp/subr.el.gz
(defun match-string (num &optional string)
"Return the string of text matched by the previous search or regexp operation.
NUM specifies the number of the parenthesized sub-expression in the last
regexp whose match to return. Zero means return the text matched by the
entire regexp or the whole string.
The return value is nil if NUMth pair didn't match anything, or if there
were fewer than NUM sub-expressions in the regexp used in the search.
STRING should be given if the last search was by `string-match'
on STRING. If STRING is nil, the current buffer should be the
same buffer as the one in which the search/match was performed.
Note that many functions in Emacs modify the match data, so this
function should be called \"close\" to the function that did the
regexp search. In particular, saying (for instance)
`M-: (looking-at \"[0-9]\") RET' followed by `M-: (match-string 0) RET'
interactively is seldom meaningful, since the Emacs command loop
may modify the match data."
(declare (side-effect-free t))
(if (match-beginning num)
(if string
(substring string (match-beginning num) (match-end num))
(buffer-substring (match-beginning num) (match-end num)))))