我在elisp工作,我有一个代表项目列表的字符串.字符串看起来像
"apple orange 'tasty things' 'my lunch' zucchini 'my dinner'"
而我正试图把它拆分成
("apple" "orange" "tasty things" "my lunch" "zucchini" "my dinner")
这是一个熟悉的问题.解决问题的障碍不在于正则表达式,更多的是关于elisp的具体细节.
我想要做的是运行一个循环:
(while (< (length my-string) 0) do-work) 那do-work是:
\('[^']*?'\|[[:alnum:]]+)\([[:space:]]*\(.+\)来my-string\1到我的结果列表my-string到\2但是,我无法弄清楚如何获得split-string或replace-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")
奖励:它还允许使用"\"转义引号,并且如果引号不平衡将报告它(到达字符串的末尾,但没有找到打开的引号的匹配).