如何捕获在elisp中拆分字符串的结果?

Bri*_*ell 3 regex emacs elisp

我在elisp工作,我有一个代表项目列表的字符串.字符串看起来像

"apple orange 'tasty things' 'my lunch' zucchini 'my dinner'"
Run Code Online (Sandbox Code Playgroud)

而我正试图把它拆分成

("apple" "orange" "tasty things" "my lunch" "zucchini" "my dinner")
Run Code Online (Sandbox Code Playgroud)

这是一个熟悉的问题.解决问题的障碍不在于正则表达式,更多的是关于elisp的具体细节.

我想要做的是运行一个循环:

  • (while (< (length my-string) 0) do-work)

do-work是:

  • 应用正则表达式\('[^']*?'\|[[:alnum:]]+)\([[:space:]]*\(.+\)my-string
  • 附加\1到我的结果列表
  • 重新绑定my-string\2

但是,我无法弄清楚如何获得split-stringreplace-regexp-in-string做到这一点.

如何将此字符串拆分为可以使用的值?

(或者:"哪个内置的emacs功能可以做到这一点我还没找到?")

小智 5

类似的东西,但没有正则表达式:

(defun parse-quotes (string)
  (let ((i 0) result current quotep escapedp word)
    (while (< i (length string))
      (setq current (aref string i))
      (cond
       ((and (char-equal current ?\ )
             (not quotep))
        (when word (push word result))
        (setq word nil escapedp nil))
       ((and (char-equal current ?\')
             (not escapedp) 
             (not quotep))
        (setq quotep t escapedp nil))
       ((and (char-equal current ?\')
             (not escapedp))
        (push word result)
        (setq quotep nil word nil escapedp nil))
       ((char-equal current ?\\)
        (when escapedp (push current word))
        (setq escapedp (not escapedp)))
       (t (setq escapedp nil)
        (push current word)))
      (incf i))
    (when quotep
      (error (format "Unbalanced quotes at %d"
                     (- (length string) (length word)))))
    (when word (push result word))
    (mapcar (lambda (x) (coerce (reverse x) 'string))
            (reverse result))))

(parse-quotes "apple orange 'tasty things' 'my lunch' zucchini 'my dinner'")
("apple" "orange" "tasty things" "my lunch" "zucchini" "my dinner")

(parse-quotes "apple orange 'tasty thing\\'s' 'my lunch' zucchini 'my dinner'")
("apple" "orange" "tasty thing's" "my lunch" "zucchini" "my dinner")

(parse-quotes "apple orange 'tasty things' 'my lunch zucchini 'my dinner'")
;; Debugger entered--Lisp error: (error "Unbalanced quotes at 52")
Run Code Online (Sandbox Code Playgroud)

奖励:它还允许使用"\"转义引号,并且如果引号不平衡将报告它(到达字符串的末尾,但没有找到打开的引号的匹配).