Function: PARSE-CSV-STRING

Documentation

Parse a csv line into a list of strings using seperator as the column seperator and quote as the string quoting character.

Source

(defun parse-csv-string (line &key (separator #\,) (quote #\"))
  "Parse a csv line into a list of strings using seperator as the
  column seperator and quote as the string quoting character."
  (let ((items '())
        (offset 0)
        (current-word (make-array 20
                                  :element-type 'character
                                  :adjustable t
                                  :fill-pointer 0))
        (state :read-word))
    (loop
       (when (= offset (length line))
         ;; all done
         (ecase state
           (:in-string
            (error "Unterminated string."))
           (:read-word
            (return-from parse-csv-string
              (nreverse (cons current-word items))))))
       (cond
         ((char= separator (aref line offset))
          (ecase state
            (:in-string
             (vector-push-extend (aref line offset) current-word))
            (:read-word
             (push current-word items)
             (setf current-word (make-array 20
                                            :element-type 'character
                                            :adjustable t
                                            :fill-pointer 0)))))
         ((char= quote (aref line offset))
          (ecase state
            (:in-string
             (setf state :read-word))
            (:read-word
             (setf state :in-string))))
         (t
          (vector-push-extend (aref line offset) current-word)))
       (incf offset))))
Source Context