1

I have a list of strings for example:

("2019_FOO_BAR.1_12"
 "2019_FOO_BAR.1_13"
 "2018_FOO_BAR.1_12"
 "2019_FOO_XYZ.1_14"
 "2017_FOO_BAR.1_14"
 "2017_FOO_XYZ.1_12"
 "2019_FOO_XYZ.1_13")

I want to group them by common substring after first underscore and before the dot.

In this example I have 2 unique substrings FOO_BAR and FOO_XYZ. But longer list may have N unique substrings.

I want the result to look like this:

(["2019_FOO_BAR.1_12" "2019_FOO_BAR.1_13" "2018_FOO_BAR.1_12" "2017_FOO_BAR.1_14"]
 ["2017_FOO_XYZ.1_12" "2019_FOO_XYZ.1_13" "2019_FOO_XYZ.1_14"])

So each substring is grouped in a separate list

1
  • What have you tried so far? Commented Aug 20, 2019 at 18:18

2 Answers 2

4

I think you are looking for a group-by

(def test-data '("2019_FOO_BAR.1_12"
                 "2019_FOO_BAR.1_13"
                 "2018_FOO_BAR.1_12"
                 "2019_FOO_XYZ.1_14"
                 "2017_FOO_BAR.1_14"
                 "2017_FOO_XYZ.1_12"
                 "2019_FOO_XYZ.1_13"))


(defn string-to-key [^String input-string]
  (let [first-spliter (.indexOf input-string "_" )
        second-spliter (.indexOf input-string "." )]
    (.subSequence input-string (+ 1 first-spliter) second-spliter)))

So you can get exactly what you are looking for with:

(vals (group-by string-to-key test-data))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was thinking using group-by but wasn't sure about splitting function implementation.
4

good candidate for regex:

user> (vals (group-by (partial re-find #"_.*?\.") data))

;; => (["2019_FOO_BAR.1_12"
;;      "2019_FOO_BAR.1_13"
;;      "2018_FOO_BAR.1_12"
;;      "2017_FOO_BAR.1_14"]
;;     ["2019_FOO_XYZ.1_14" "2017_FOO_XYZ.1_12" "2019_FOO_XYZ.1_13"])

2 Comments

Thanks. Nice and concise!
Regular Expressions: Now You Have Two Problems :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.