[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Chicken-users] irregex-replace return value
From: |
Michele La Monaca |
Subject: |
Re: [Chicken-users] irregex-replace return value |
Date: |
Wed, 5 Mar 2014 20:40:16 +0100 |
On Tue, Mar 4, 2014 at 10:19 AM, Michele La Monaca
<address@hidden> wrote:
> After some more mulling, I concluded that it would be even more
> convenient to have a generalised version of irregex-replace-match
> which also accepts lists of matches:
>
> (irregex-replace-match match-or-list-of-matches str o)
Some proof-of-concept code if anyone wants to play with the idea:
(define (irregex-replace-match m str o)
(if (irregex-match-data? m) (set! m (list m)))
(if (null? m)
str
(string-append
(substring str 0 (irregex-match-start-index (car m) 0))
(let loop ((matches m))
(if (null? matches)
""
(let ((m (car matches)))
(string-append (apply string-append
(reverse (irregex-apply-match m o)))
(substring str
(irregex-match-end-index m 0)
(if (pair? (cdr matches))
(irregex-match-start-index
(cadr matches) 0)
(string-length str)))
(loop (cdr matches)))))))))
(define (irregex-search/all irx str #!optional m-max)
(irregex-fold
irx
(lambda (i m acc) (cons m acc))
'()
str
(lambda (i acc)
(reverse (if (and m-max (< m-max (length acc)))
(list-tail acc (- (length acc) m-max))
acc)))))
(define (my-irregex-replace/all irx str . o)
(let ((ms (irregex-search/all irx str)))
(and (pair? ms) (irregex-replace-match ms str o))))
(define (irregex-replace/nth n irx str . o)
(let ((m (irregex-search/all irx str n)))
(if (> n (length m))
str
(irregex-replace-match (list-ref m (- n 1)) str o))))
(define (irregex-replace/2nd-and-4th irx str . o)
(let ((ms (irregex-search/all irx str 4)))
(if (and (pair? ms) (>= (length ms) 4))
(irregex-replace-match (list (list-ref ms 1) (list-ref ms 3)) str o)
str)))
(my-irregex-replace/all 'digit "1,2,3,4,5" "integer")
=> "integer,integer,integer,integer,integer"
(irregex-replace/nth 4 'digit "1,2,3,4,5" "notprime")
=> "1,2,3,notprime,5"
(irregex-replace/2nd-and-4th 'digit "1,2,3,4,5" "pair")
=> "1,pair,3,pair,5"
Michele