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 the function match-data
. However, elisp provide many more direct functions to extract data stored in match-data
.
Here are the most useful ones.
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)
same as
match-string
but 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)
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)) ;; lots sample text 123 abc ;; "123"
match-end
-
(match-end n)
return the end position of the nth captured string of last regex search.
Emacs Lisp, 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: Tip: 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