;;; Regular expression utilities: adds a few more primitives. (module re mzscheme (require (lib "pregexp.ss")) (provide (all-defined)) ;;; Calls function for each match in the insert string. (define (find/for-each regexp func string) (let loop ((start 0)) (let ((match (pregexp-match-positions regexp string start))) (if (not match) (void) (begin (func string match) (loop (cdar match))))))) ;;; Returns a list of all matches. (define (findall regexp string) (let* ((result ()) (add-match (lambda (string pairs) (set! result (cons (extract-match string pairs) result))))) (find/for-each regexp add-match string) (reverse result))) ;;; Provides a substitution function that calls the rep function on ;;; each match. (define (sub regexp repl-function insert-string) (let ((buffer (open-output-string)) (i 0)) (let ((replace-f (lambda (string pairs) (display (substring insert-string i (caar pairs)) buffer) (display (repl-function insert-string pairs) buffer) (set! i (cdar pairs))))) (find/for-each regexp replace-f insert-string) (display (substring insert-string i) buffer) (get-output-string buffer)))) ;;; Extracts the matching string out. (define (extract-match string pairs) (substring string (caar pairs) (cdar pairs))))