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

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.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest