Skip to content

Instantly share code, notes, and snippets.

@devn
Created March 4, 2011 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devn/854070 to your computer and use it in GitHub Desktop.
Save devn/854070 to your computer and use it in GitHub Desktop.
clojure regex
(defn extract-sexps
"Extracts s-exp from a string."
[#^String string]
(second
(reduce (fn [[exp exps state cnt] c]
(cond
(= state :escape)
[(.append exp c) exps :string cnt]
(= state :string) (cond
(= c \")
[(.append exp c) exps :code cnt]
(= c \\)
[(.append exp c) exps :escape cnt]
(= c \\)
[(.append exp c) exps :escape cnt]
:else
[(.append exp c) exps :string cnt])
(and (= cnt 1) (= c \)))
[(java.lang.StringBuilder.) (cons (str (.append exp c)) exps) :text 0]
(= c \()
[(.append exp c) exps :code (inc cnt)]
(and (> cnt 1) (= c \)))
[(.append exp c) exps :code (dec cnt)]
(and (> cnt 0) (= c \"))
[(.append exp c) exps :string cnt]
(> cnt 0)
[(.append exp c) exps :code cnt]
:else [exp exps state cnt]))
[(java.lang.StringBuilder.) '() :text 0]
string)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment