In ClojureScript, how to split string around a regex and keep the matches in the result, without using lookaround?

I want to split a string on an arbitrary regular expression (similar to ) but keep the matches in the result. One way to do this is with lookaround in the regex but this doesn't work well in ClojureScript because it's not supported by all browsers.

In my case, the regex is #"\{\{\s*[A-Za-z0-9_\.]+?\s*\}\}")

So for example, foo {{bar}} baz should be split into ("foo " "{{bar}}" " baz").

Thanks!

1 Answer

One possible solution is to choose some special character as a delimiter, insert it into the string during replace and then split on that. Here I used exclamation mark:

Require: [clojure.string :as s]

(-> "foo {{bar}} baz" (s/replace #"\{\{\s*[A-Za-z0-9_\.]+?\s*\}\}" "!$0!") (s/split #"!"))
=> ["foo " "{{bar}}" " baz"]

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like