regexp.scm

From: Tom Tromey <tromey_at_busco.lanl.gov>
Date: Sat, 24 Sep 94 15:12:56 MDT

Here is the Scheme part of the regexp package.

Tom
---
tromey_at_busco.lanl.gov             Member, League for Programming Freedom
Sadism and farce are always inexplicably linked.
	-- Alexander Theroux
;;
;; regexp.scm -- More interfaces to regular expressions.
;; tromey Fri Jul 29 1994
;;
;; TO DO:
;; make this work in other schemes.
(if (not (symbol-bound? 'string->regexp))
    ;; Must load package.
    (load "sregexp.so"))
;;
;; Do a regular expression match of REGEXP against STRING.  On match,
;; follow instructions in SUBST to rewrite string.  Return new string.
;; SUBST is a list whose elements are in one of three forms:
;; 1. A string.  The string is appended to the result.
;; 2. An integer, n.  The nth sub-match is appended.
;; 3. A procedure.  The procedure is called with the match result and
;; the string as arguments.  The return result of the procedure is
;; appended.
;;
;; regexp-substitute returns the result string, or #f if no match.
;;
;; regexp-substitute-all is like regexp-substitute, but it works on
;; all matching substrings.
;; FIXME do this so that the functions share an environment.  Is there
;; a better way?
(define regexp-substitute #f)
(define regexp-substitute-all #f)
(let
    ;; subst-match does one substitution, given a match, a string, and
    ;; a substitution list.
    ((subst-match (lambda (match string subst)
		    (apply string-append
			   (map (lambda (what)
				  (cond
				   ((string? what) what)
				   ((procedure? what)
				    (what match string))
				   ((integer? what)
				    (substring string
					       (match-beginning match what)
					       (match-end match what)))
				   (else
				    ;; This will force an error in
				    ;; string-append.
				    #f)))
				subst)))))
  (set! regexp-substitute (lambda (regexp string subst)
			    (let ((match (regexp string)))
			      (if match
				  (subst-match match string subst)
				  #f))))
  (letrec
      ;; do-subst does the work for regexp-substitute-all
      ((do-subst (lambda (regexp string subst)
		   (let ((match (regexp string)))
		     (if match
			 (append
			  (list (substring string 0 (match-beginning match 0))
				(subst-match match string subst))
			  (do-subst
			   regexp
			   (substring string
				      (match-end match 0)
				      (string-length string))
			   subst))
			 (list string))))))
    (set! regexp-substitute-all
	  (lambda (regexp string subst)
	    (apply string-append (do-subst regexp string subst))))))
;;
;; Return a regular expression string that matches STRING exactly, and
;; nothing else.
;;
(define regexp-quote
  (let ((regexp (string->regexp "[][\\|.?+*()]")))
    (lambda (string)
      (regexp-substitute-all regexp string '("\\" 0)))))
Received on Sat Sep 24 1994 - 23:14:20 CEST

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