[racket] string-strip

From: Marijn (hkBst at gentoo.org)
Date: Tue Dec 27 12:55:25 EST 2011

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

Sometimes I wish for python-like string-strip to be a standard
function. For example when I want to parse a list of numbers from a
text-field, I could get the string value of the text-field, strip
space from the beginning and end, split on whitespace, map
string->number over it and check the result with `every'.

Is there a better way? If not then perhaps some form of string-strip
could be added (perhaps under regexp-strip name?) since it isn't
exactly extremely simple unless you're a regexp wizard.

Marijn

Some code (ter leering ende vermaak):

#lang racket

(require rackunit (only-in srfi/1 every))

(define (string-strip string (strip "[:space:]"))
  (define rexp
    (pregexp (regexp-replace*
	      "strip"
	      "^[strip]*(.*?)[strip]*$"
	      strip)))
  (cadr (regexp-match rexp string)))

(check-equal? (string-strip " strip this	 ") "strip this")

(define (string-split string (split "[[:space:]]+"))
  (regexp-split (pregexp split) (string-strip string)))

(check-equal? (string-split "  12. .12
  34") '("12." ".12" "34"))

(define (string->number-list string)
  (map string->number (string-split string)) )

(check-equal? (string->number-list " 2003 2005  2007\t  ") '(2003 2005
2007))

(define (list-of-years? lst)
  (every exact-positive-integer? lst))

(check-equal? (string->number "not a number") #f)
(check-equal? (list-of-years? '(2003 3004 43)) #t)
(check-equal? (list-of-years? '(45 #f 20)) #f)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.18 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAk76Bo0ACgkQp/VmCx0OL2xxHwCgmzdAEYEIg92eigYetBw6EWB1
JeQAnRHlTA3C+ZCJnz83lj6YkGCEA3Oy
=spER
-----END PGP SIGNATURE-----


Posted on the users mailing list.