Emacs Lisp: Regex Functions
Regex Functions on Buffer
(search-forward STRING &optional BOUND NOERROR COUNT)
re-search-forward, but using plain text to search, not regex.
(re-search-forward REGEXP &optional BOUND NOERROR COUNT)
Search a regex pattern starting from cursor position, towards right.
If found, move cursor to the end of matched text.
- BOUND → is nil or a positive integer (cursor position). Positive integer means don't search beyond it.
- NOERROR → value is nil, t, or something else e.g.
1. If nil, then abort with error if pattern is not found. If t, don't abort, and leave cursor at original position. If other value, no error, and move cursor to end of search text.
- COUNT → default to 1. Else, search that many times. If negative, search backward.
(let ((case-fold-search nil)) (re-search-forward "[0-9]+")) ;; 100 cats
re-search-forwardbut search backward, however, searching backward may stop at a position that's not maximally matched by pattern.
(skip-chars-forward STRING &optional LIM)
Move cursor forward, stopping before a char not in STRING, but not beyond position LIM.
STRING is like the inside of a
[chars]in a Regular Expression Syntax except that
]is never special and
Returns the distance traveled, either zero or positive.
(skip-chars-backward STRING &optional LIM)
Regex Function for Matching in a String
(string-match REGEXP STRING &optional START)
Return the index of beginning of first match in STRING. Return nil if no match.
(string-match "3" "xx3x" ) ;; 2
(replace-regexp-in-string REGEXP REP STRING &optional FIXEDCASE LITERAL SUBEXP START)
Replace string by regex.
(replace-regexp-in-string "</*div>" "<p>" "<div>something</div>") ;; return ;; "<p>something<p>"
Get Captured Group
(replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING SUBEXP)
Replace the matched pattern of previous regex function call.
in replace string NEWTEXT, backslash has the following special meaning, unless LITERAL is true:
⚠ WARNING: each backslash below should be double in string.
\&→ whole matched text.
\N→ nth captured group.
\\→ literal backslash.
Case conversion are not applied.
(let ((case-fold-search nil)) (re-search-forward "x\\([0-9]+\\)" nil t) (replace-match "ID \\1")) ;; x803 ;; after running the code above, the x became ID
Emacs Regular Expression
- Regular Expression
- Regex Syntax
- About Quoting Regex
- Case Sensitivity
- How to Insert a Tab or Newline
- Wildcards vs Regex