On Wed, Jun 24, 2009 at 6:13 PM, CuppoJava<patrickli_2...@hotmail.com> wrote: > > I need to dynamically create a regex, and would really like to be able > to use Clojure's built-in regex syntax. But I don't know how to go > about it. > > My regex is: #"(.*?)(\(image .*)" > > except instead of "image", I need to dynamically insert an array of > possible strings to match. > > ie. given ["image" "buffer" "spacer"] > > I need to produce #"(.*?)(\((?:image|buffer|spacer) .*)" > > Is there a nice way of doing this
No, there's really not. I'd love to see a s-expry DSL for string parsing that was as powerful and nearly as compact as regex that would be able to do this kind of thing. ...but until then you can convert strings to regex patterns using re-pattern, and build the strings with the various tools at hand. One handy tool is the #"" syntax itself, which works great for building parts of a larger regex as long as those parts are legal regex themselves. Other tools can be found in contrib. Here the best I've come up with for your example: (use '[clojure.contrib.str-utils :only [str-join]]) (defn my-regex [words] (re-pattern (str #"(.*?)" ; stands alone, so #"" works "(\\((?:" ; regular string, so \ must be escaped (str-join "|" words) ").*)"))) user=> (my-regex ["image" "buffer" "spacer"]) #"(.*?)(\((?:image|buffer|spacer).*)" --Chouser --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---