Using emacs 25.3.1
, I am trying to access the match data after I search a string with string-match
. But the match data is wrong. To find out why I tried out the manual's simple example.
(string-match "\\(qu\\)\\(ick\\)"
"The quick fox jumped quickly.")
;0123456789
(match-string 0 "The quick fox jumped quickly.")
When running this example I get the following results:
4
Debugger entered--Lisp error: (args out of range "The quick fox jumped quickly." 1513 1515)
I think this is because I used string-match
on a string before executing this example. However, I expected match-data
to only consider my last string-match
search and return "quick".
Surprisingly, this behavior persists across sessions. If, after getting this error, I startup emacs with emacs -Q
(no init file), and I paste the "quick fox" example and execute it I get the same error (with updated numbers).
I tried to reset match data myself using set-match-data
, however that hasn't been working.
(match-data) ; => (1520 1520)
(set-match-data (list 0 0)) ; => nil
(match-data) ; => (1547 1547)
How can I reset the match data myself to produce expected values from string-match
search?
C-x C-e
or similar?eval-print-last-sexp
.eval-print-last-sexp
multiple times in the course of a single test -- e.g. once for(string-match...)
and then again for(match-string...)
-- then Emacs is doing a heap of things between each of those commands, and you cannot assume that the match data was not affected in that time. You want to wrap the code in(progn ...)
or similarly ensure that a single use ofeval-print-last-sexp
runs all the code you are testing.