[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
regex-split for Guile
From: |
William James |
Subject: |
regex-split for Guile |
Date: |
Mon, 7 Mar 2011 06:57:00 -0800 (PST) |
Tested under Guile 1.8.7.
(define (regex-split regexp str . options)
(let ((keep #f) (trim #f))
(if (member 'keep options)
(begin (set! options (delete 'keep options))
(set! keep #t)))
(if (member 'trim options)
(begin (set! options (delete 'trim options))
(set! trim #t)))
(let* ((matches (apply list-matches regexp str options))
(indices
(append '(0)
(fold-right
(lambda (m acc) (cons (match:start m)
(cons (match:end m) acc))) '()
matches)
(list (string-length str))))
(substrings
(pair-fold-right
(lambda (lst accum)
(if (or (even? (length lst))
(and keep (> (length lst) 1)))
(cons (apply substring str (take lst 2)) accum)
accum))
'()
indices)))
(if trim
(reverse! (drop-while string-null?
(reverse! (drop-while string-null? substrings))))
substrings))))
guile> (regex-split "[-x]+" "foo--x--bar---what--")
("foo" "bar" "what" "")
guile> (regex-split "[-x]+" "foo--x--bar---what--" 'trim)
("foo" "bar" "what")
guile> (regex-split "[-x]+" "foo--x--bar---what" 'keep)
("foo" "--x--" "bar" "---" "what")
- regex-split for Guile,
William James <=