Doesn't Clojure support Named capturing group?

Doing one of the Exercism tasks, I found out I can’t avail of “named capturing groups” in the regular expressions.


(def log-entry "[WARNING]:  Disk almost full\r\n")

(def log-pattern-1 #"\[(?<level>ERROR|WARNING|ERROR)\]:\s*(?<message>.*)\s*$")

(re-matches log-pattern-1 log-entry)
;; => ["[WARNING]:  Disk almost full\r\n" "WARNING" "Disk almost full"]

It produces the matches, but I can’t use the “named capturing groups” in anyways: or can I?

At least neither with re-matchers nor with re-seq.

Am I missing something? I’m asking because Java does support them… no?

It does. Use re-matcher to create Matcher, then use .find to activate (or re-find) and then you can use .group:

(let [fm (doto (re-matcher log-pattern-1 log-entry) .find)]
  (println (.group fm "level"))
  (println (.group fm "message")))

If you want to return all groups, you can use re-groups (full match + groups):

(let [fm (doto (re-matcher log-pattern-1 log-entry) .find)]
  (re-groups fm))

Thank you very much. I think I didn’t even consider it because some warnings I’ve read about it in the past. Here is just one of them from Practicalli:

Java’s regular-expression engine includes a Matcher object that mutates in a non-thread-safe way as it walks through a string finding matches. This object is exposed by Clojure via the re-matcher function and can be used as an argument to re-groups and the single-parameter form of re-find. Avoid these unless you’re certain you know what you’re doing. These dangerous functions are used internally by the implementations of some of the recommended functions described earlier, but in each case they’re careful to disallow access to the Matcher object they use. Use matchers at your own risk, or better yet don’t use them directly at all.

It think I had encounter similar warnings somewhere else.

Anyways, the support is there. Maybe it would be nice that the re-seq and re-matchers support that just for those who want to use the feature, but not using the “non-thread-safe” way.

Thank you very much.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.