Check if String contains substring in clojure
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?
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
Clojure 1.8 has introduced includes? function.
(use '[clojure.string :as s])
(s/includes? "abc" "ab") ; true
(s/includes? "abc" "cd") ; false