3

According to match-string help:

Value is nil if NUMth pair didn't match

In fact:

(string-match "\\(hullo\\)" "hello")
(match-string 1 "hello")

gives nil

Also, a NUM

Zero means the entire text matched by the whole regexp or whole string.

Therefore, given:

(string-match "hullo" "hello")
(match-string 0 "hello")

I'd expect a nil, as above, since since the 0-th pair didn't match.
Instead, I get the Lisp error args-out-of-range.

1
  • Please file a doc bug to ask for improvement: M-x report-emacs-bug.
    – Drew
    Apr 8, 2016 at 15:29

1 Answer 1

3

The documentation of string-match states that you can use match-string to extract substrings matched by the parenthesis constructions. There is no mention of the whole string.

string-match is a built-in function in `C source code'.

(string-match REGEXP STRING &optional START)

Return index of start of first match for REGEXP in STRING, or nil.
Matching ignores case if `case-fold-search' is non-nil.
If third arg START is non-nil, start search at that index in STRING.
For index of first char beyond the match, do (match-end 0).
`match-end' and `match-beginning' also give indices of substrings
matched by parenthesis constructs in the pattern.

You can use the function `match-string' to extract the substrings
matched by the parenthesis constructions in REGEXP.

The documentation of match-stringis:

match-string is a compiled Lisp function in `subr.el'.

(match-string NUM &optional STRING)

Return string of text matched by last search.
NUM specifies which parenthesized expression in the last regexp.
 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
Zero means the entire text matched by the whole regexp or whole string.
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
the search/match was performed in.

There whole string refers to the case that you search with search-forward instead of re-search-forward. It does not refer to the case that you used string-match.

You get the behaviour described in your question by (when (string-match "hullo" str) (match-string str)). This returns nil on (setq str "hello") and "hullo" on (setq str "hullo").

You are right. The documentation could be more clear about this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.