52

I need to check if a java String contains a substring in my tests.

This doesn't work because java strings are not collections:

(deftest test_8
    (testing "get page from sputnik"
        (let [
            band "Isis"
            page (get-sputnikpage-for-artist band)
            ]
            (is (contains? band "Isis")))));does NOT work

Is there a way to convert java strings into collections? Or can I check for substring occurences in other ways?

1
  • 4
    Be aware that contains? does NOT check the existence of values, but existence of keys (maps) or indices (vectors and strings). One of the most common pitfalls in Clojure function naming. Both (contains? [1 2] 2) and (contains? "12" 2) => false because neither has an index 2 (only 0 & 1) Commented Oct 15, 2014 at 16:32

3 Answers 3

78

The easiest way is to use the contains method from java.lang.String:

(.contains "The Band Named Isis" "Isis")

=> true

You can also do it with regular expressions, e.g.

(re-find #"Isis" "The Band Named Isis")

=> "Isis"

(re-find #"Osiris" "The Band Named Isis")

=> nil

If you need your result to be true or false, you can wrap it in boolean:

(boolean (re-find #"Osiris" "The Band Named Isis"))

=> false

Sign up to request clarification or add additional context in comments.

Comments

65

Clojure 1.8 has introduced includes? function.

(use '[clojure.string :as s])
(s/includes? "abc" "ab") ; true
(s/includes? "abc" "cd") ; false

Comments

6

Strings are seqable:

(seq "Hello") ;;=> (\H \e \l \l \o)

... so you could use the sequence library to find a match:

(defn subsumes [main sub]
  (some
   (partial = (seq sub))
   (partition (count sub) 1 main)))

(subsumes "Hello" "ll") ;;=>> true

... but it's simpler and much faster to do as Diego Basch suggested.

Comments

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.