Elisp: Match Data (Regex Result)
What is Match Data
Elisp: 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 several functions.
Get Match String (Captured Groups)
Whenever you call regex functions such as
• re-search-forward
• string-match
the captured text is stored in match-string
.
match-string
-
(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.
- etc.
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-string-no-properties
-
(match-string-no-properties n)
similar to
match-string
but without Text Properties
Get Begin/End Positions (of Captured Groups)
match-beginning
-
(match-beginning n)
return the beginning position of the nth captured string of last regex search.
0 means the whole match.
(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)) ;; sample text 123 abc ;; "123"
match-end
-
(match-end n)
return the end position of the nth captured string of last regex search.
Other Match Data Functions
save-match-data
-
(save-match-data &rest BODY)
save and restore match data.
match-substitute-replacement
match-data
set-match-data
Reference
Elisp, Regex in Lisp Code
- Elisp: Regular Expression
- Elisp: Regex Functions
- Emacs: Regular Expression Syntax
- Elisp: Regex Backslash in Lisp Code
- Elisp: Case Sensitivity (case-fold-search)
- Elisp: Find Replace Text in Buffer
- Elisp: Match Data (Regex Result)
- Elisp: Unicode Escape Sequence
- Elisp: Convert Regex to Lisp Regex String
- Elisp: How to Test Regex
- Elisp: Regex in Readable Syntax, Package Rx
- Elisp: Regex Named Character Class and Syntax Table
- Emacs Regex vs Regex in Python, JavaScript, Java