Search

Dark theme | Light theme

April 22, 2020

Clojure Goodness: Check Substring Is Part Of String

Sometimes we want to see if a string is part of another string. Or if the string value starts or ends with a certain string. In Clojure we can use the includes? function from the clojure.string namespace to check if a string is part of another string value. To see if a string starts with a certain value we can use the starts-with? function from the clojure.string namespace. And to check if a string ends with a given value we use ends-with? from the same namespace.

In the next example code we use these functions and also add a matches? function to check if a string matches with a regular expression defined in a string:

(ns mrhaki.string.includes
  (:require [clojure.string :as str]
            [clojure.test :refer [is]]))

;; String to check.
(def s "Clojure is cool!")

;; Check if given value is part of the string.
(is (true? (str/includes? s "cool")))
(is (false? (str/includes? s "boring")))

;; Check string starts with given value.
(is (true? (str/starts-with? s "Clojure")))
(is (false? (str/starts-with? s "Groovy")))

;; Check string ends with given value.
(is (true? (str/ends-with? s "cool!")))

;; Helper function to see if string with regular expression
;; matches a given string value using java.lang.String#matches.
(defn matches? 
  "Return true when string `re` with regular expression
  matches for value `s`, false otherwise."
  [^CharSequence s ^CharSequence re] 
  (. s matches re))

(is (true? (matches? s ".*is.*")))
(is (false? (matches? s "cool")))

Written with Clojure 1.10.1.