emacs-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: string-strip


From: Lars Hansen
Subject: Re: string-strip
Date: Mon, 19 Jun 2006 19:59:52 +0200
User-agent: Debian Thunderbird 1.0.2 (X11/20060423)

Richard Stallman wrote:

>    (defun my-string-strip (str)
>      "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) 
> space."
>      (string-match "\\`\\s-*\\(.*?\\)\\s-*\n?\\'" str)
>      (match-string 1 str))
>
>    (string-strip "asdf ")"asdf"
>    (string-strip " asdf")"asdf"
>    (string-strip " asdf ")"asdf"
>
>It is a useful function and a simple one, and it won't delay the
>release much.  If you write the manual and NEWS changes for it first,
>I will say yes.
>  
>
I suggest some changes:

1. Allow newlines in STR.
2. Treat newlines as white space.
3. Return nil when resulting string is empty.
4. Use save-match-data.

This implementation works that way:

(defun string-strip (str)
  "Return STR with leading and traling white space removed.
If the resulting str has zero lenght, nil is returned."
  (save-match-data
    (string-match
"\\`[[:space:]\n]*\\(\\(.\\|\n\\)*?\\)[[:space:]\n]*\\'" str)
    (let ((result (match-string 1 str)))
      (unless (zerop (length result))
        result))))

Here are some tests:

(my-string-strip " foo ")      => "foo"
(my-string-strip " foo\n ")    => (args-out-of-range " foo\n" 8 9)
(my-string-strip " \nfoo ")    => (args-out-of-range " \nfoo" 8 9)
(my-string-strip " foo\nbar ") => " "
(my-string-strip " ")          => ""

(string-strip " foo ")         => "foo"
(string-strip " foo\n ")       => "foo"
(string-strip " \nfoo ")       => "foo"
(string-strip " foo\nbar ")    => "foo\nbar"
(string-strip " ")             => nil





reply via email to

[Prev in Thread] Current Thread [Next in Thread]