Re: Behaviour of regexp-replace-all

From: Sean Slattery <jslttery_at_GS148.SP.CS.CMU.EDU>
Date: Fri, 26 May 1995 11:43:29 -0400

OK - Here's my suggestion for a more intuitive regexp-replace-all - I've
copied the relevant section from regexp.stk and defined a
regexp-replace-all-mine - unlike the previous regexp-replace-all, it
"precompiles" the search string if required and then recurses.

S.





;; Had to write this to get intuitive regular expression substitution.

(define regexp-replace-all-mine #f)

(let ()
  ;; Utility function
  ;; Given a string and a set of substitutions, return the substitued string
  (define (replace-submodels string subst match)
    (if (= (length match) 1)
        ;; There is no sub-model
        subst
        ;; There are at least one sub-model to replace
        (let Loop ((subst subst))
          (let ((pos ((string->regexp "\\\\[0-9]") subst)))
            (if pos
                ;; At least one \x in the substitution string
                (let* ((index (+ (caar pos) 1))
                       (val (string->number (substring subst index (+ index 1)))))
                  (if (>= val (length match))
                      (error "regexp-replace: cannot match \\~A in model" val)
                      ;; Build a new subst with the current \x remplaced by
                      ;; its value. Iterate for further \x
                      (Loop (replace-string subst
                                            (caar pos)
                                            (cadar pos)
                                            (apply substring string
                                                   (list-ref match val))))))
                ;; No \x in substitution string
                subst)))))
  (set! regexp-replace-all-mine
        (lambda (pat str subst)
          (letrec ((regexp-replace-all-r
                    (lambda (regexp str subst)
                      (let ((match (regexp str)))
                        (if match
                            (string-append
                             (substring str 0 (caar match))
                             (replace-submodels str subst match)
                             (regexp-replace-all-r
                              regexp
                              (substring str (cadar match) (string-length str))
                              subst))
                          str)))))
                  (let ((regexp (cond
                                 ((regexp? pat) pat)
                                 ((string? pat) (string->regexp pat))
                                 (else (error "regexp-replace: Bad pattern '~1'" pat)))))
                    (regexp-replace-all-r regexp str subst))))))
Received on Fri May 26 1995 - 17:45:43 CEST

This archive was generated by hypermail 2.3.0 : Mon Jul 21 2014 - 19:38:59 CEST