Replace Regexp In String
Mimics the GNU Emacs function with the same name:
(define (replace-regexp-in-string regexp replacement string)
;; Replace all occurrences of REGEXP with REPLACEMENT in STRING.
;; If REPLACEMENT is a procedure, it is applied to the match
;; structure for the given match and should return a string to be
;; used in the result.
;; Example:
;; (replace-regexp-in-string (rx "foo") "bar" "foo foobar abc foofoo")
;; => "bar barbar abc barbar"
(regexp-substitute/global #f regexp string 'pre replacement 'post))
This one is slightly more complex.
(define (replace-regexp-in-string regexp rep string)
(cond
((string? rep)
(regexp-substitute/global #f regexp string 'pre rep 'post))
((pair? rep)
(apply regexp-substitute/global #f regexp string 'pre (append rep (list 'post))))
(else
(error '&contract replace-regexp-in-string regexp rep string))))
Examples:
> (replace-regexp-in-string (rx " ")
"-"
"foo bar")
"foo-bar"
> (replace-regexp-in-string (rx (+ alphanumeric))
'("(" 0 ")")
"foo bar")
"(foo) (bar)"
ReplaceRegexpInString - raw wiki source |
code snippets archive
|