简体   繁体   中英

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, eg

(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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM