如何从变量的末尾修剪空格

时间:2014-01-25 23:21:07

标签: emacs elisp

我正在寻找一个如何从变量末尾删除一个或多个空格的例子。

(let ((test-variable "hello "))

  (if (eq ?\s (aref test-variable (1- (length test-variable))))

    (setq test-variable "hello")))

4 个答案:

答案 0 :(得分:7)

在Emacs 24.4(将于今年晚些时候发布)中,这将更加简单:

(require 'subr-x)

(string-trim-right "some string  ")

当您等待24.4时,您可以在本地定义string-trim-right

(defun string-trim-right (string)
  "Remove trailing whitespace from STRING."
  (if (string-match "[ \t\n\r]+\\'" string)
      (replace-match "" t t string)
    string))

答案 1 :(得分:6)

简单:(car (split-string "hello ")) ==> “你好”

您还可以明确使用参数TRIM,因为文档字符串建议:

(split-string "hello   "
              split-string-default-separators
              t
              split-string-default-separators)

答案 2 :(得分:1)

或者

(replace-regexp-in-string "\s+$" "" "bar    ")
"bar"

答案 3 :(得分:1)

在更一般的情况下,您可以采取以下方法:

;; Create an utility function for this purpose
(defun strip-trailing-space (string)
   ;; We may use this twice, and `length' is an expensive operation
   (let ((last (1- (length string))))
      ;; is the last position a space?
      (if (eq ?\s (aref string last))
          ;; if so, return up to the position before it
          (subseq string 0 last)
          ;; if not, return the original string
          string)))

更通用的函数可能会接受谓词来删除多个字符或类型的字符,例如

(defun eq-space-p (char) (eq ?\s char))
(defun space-or-underline-p (char) (member char '(?\s ?_)))
(defun strip-trailing-chars (string &optional test)
  (let ((last (1- (length string))))
    (if (funcall (or test #'eq-space-p) (aref string last))
        (subseq string 0 last)
        string)))

测试:

(strip-trailing-space "hello ")   → "hello"
(strip-trailing-space "hello_")   → "hello_"

(strip-trailing-chars "hello ")   → "hello"
(strip-trailing-chars "hello_")   → "hello_"
(strip-trailing-chars "hello_"
                      #'space-or-underline-p) → "hello"

破坏性使用:

(setq test-variable (strip-trailing-space test-variable))

(NB变量的破坏性变异通常是“代码气味”,但Emacs中肯定有正当理由这样做。)