Emacs Lisp: Match Data (Regex Result)
Emacs Lisp: Regex Functions store match result in match data. Such as caputured groups, or begin/end positions of the captured pattern, or whole matched string.
Match data can be accessed by the function
match-data. However, elisp provide many more direct functions to extract data stored in
Here are the most useful ones.
Get Match String (Captured Groups)
Whenever you call regex functions such as
the captured text is stored in
(match-string NUM &optional STRING)
Return string of text matched by last search.
NUM an is integer.
- 0 means the whole matched text.
- 1 means first captured group.
- 2 means second captured group.
If the last search is buffer text search, STRING should be nil. But if last regex search is done on a string by
string-match, it should be the string that is searched.
;; example of match-string (re-search-forward "id=\\([0-9]+\\)" ) (message "%s" (match-string 1 )) ;; prints 172 ;; id=172
(setq xx "swimming in sea") (string-match "\\([a-z]+?ing\\) " xx) (match-string 1 xx) ;; "swimming"
match-stringbut without Text Properties
(let ((case-fold-search nil)) (re-search-forward "\\([0-9]+\\)") ;; lots text 123 abc (match-string-no-properties 1) ) ; "123"
Get Begin/End Positions (of Captured Groups)
return the beginning position of the nth captured string of last regex search.
(let ((case-fold-search nil) p1 p2) (re-search-forward "\\([0-9]+\\)") (setq p1 (match-beginning 1)) (setq p2 (match-end 1)) (buffer-substring-no-properties p1 p2)) ;; lots sample text 123 abc ;; "123"
return the end position of the nth captured string of last regex search.
Emacs Regular Expression
- Regular Expression
- Regex Syntax
- About Quoting Regex
- Case Sensitivity
- How to Insert a Tab or Newline
- Wildcards vs Regex