使用append从一行文本创建一个列表

时间:2013-04-16 10:01:52

标签: elisp

我想从标签分隔的一行文字中创建一个单词列表。我想基本上将线分成原子,按标签分割。

下面的代码是一种伪代码,但这是做这类事情的最佳方法吗?

这是我的第一次尝试: -

(defun get-hdr()
    ;obviously point must be positioned on correct line
    (let (mylist)
      (while(not (end-of-line)
         (while(re-search-forward ("[A-Za-z]+[^\t\n]" nil t)
           (append (match-string 1) mylist)      
         ))
      ))
   )
)

如何让我的函数返回列表,mylist?

1 个答案:

答案 0 :(得分:1)

您只需在循环结束时对其进行评估。

(defun get-hdr ()
  (let (mylist)
     (while (not (end-of-line))  ; missing closing parenthesis added
        (while (re-search-forward ("[A-Za-z]+[^\t\n]" nil t)) ; ditto
           (setq mylist (append (match-string 1) mylist)) ) ) ; note setq
     mylist) )

在这种情况下,习惯使用cons代替append;然后在最后,您可能想要反转列表。

(defun get-hdr ()
  (let (mylist)
     (while (not (end-of-line))
        (while (re-search-forward ("[A-Za-z]+[^\t\n]" nil t))
           (setq mylist (cons (match-string 1) mylist) ) ) )
     (reverse mylist)) )

另请参阅http://www.gnu.org/software/emacs/manual/html_node/elisp/Building-Lists.html,其中讨论append在更广泛的背景下的功能。

在许多情况下,您的函数不应该混淆用户的正则表达式匹配数据或缓冲区位置;考虑在let表单周围添加save-excursionsave-match-data个包装器。

但是,为了你所说的目的,也许你需要的只是

(split-string (buffer-substring-no-properties (point) (line-end-position)) "\t")

Documentation

相关问题