Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if String contains substring in clojure

Tags:

string

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?

like image 299
Luke Avatar asked Oct 15 '14 15:10

Luke


People also ask

How do you check if a string contains a substring in Clojure?

In Clojure we can use the includes? function from the clojure. string namespace to check if a string is part of another string value.

What is let in Clojure?

Clojure let is used to define new variables in a local scope. These local variables give names to values. In Clojure, they cannot be re-assigned, so we call them immutable.


1 Answers

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

like image 93
Diego Basch Avatar answered Sep 21 '22 17:09

Diego Basch