Created
March 4, 2011 02:34
-
-
Save devn/854070 to your computer and use it in GitHub Desktop.
clojure regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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