19 Strings and Regular Expressions

 

One of the most common programming tasks is transformation and manipulation of strings. Regular expressions are also an essential tool to process strings and is included in this section.

19.1  str

str is one of the most used Clojure functions. It takes one or more strings and returns their concatenation:

(str "Should " "this " "be " "a " "single " "sentence?") ; #1
;; "Should this be a single sentence?"

But str is not limited to strings, because it converts any non-string before concatenating it. It is common to see str used on all sort of values, because every type in Clojure (inheriting this behavior from Java) contains at least a default conversion to string. Sometimes this behavior is not desirable, as in the case of lazy sequences:

(str :a 'b 1e8 (Object.) [1 2] {:a 1}) ; #1
;; ":ab1.0E8java.lang.Object@dd2856e[1 2]{:a 1}"

(str (map inc (range 10))) ; #2
;; "clojure.lang.LazySeq@c5d38b66"

(pr-str (map inc (range 10))) ; #3
;; "(1 2 3 4 5 6 7 8 9 10)"

Another typical use of str is on collections with either apply or reduce. The resulting string is equivalent to the concatenation of all the items in the input collection:

(apply str (range 10)) ; #1
;; "0123456789"

(reduce str (interpose "," (range 10))) ; #2
;; "0,1,2,3,4,5,6,7,8,9"

19.2  join

19.3  replace, replace-first, re-quote-replacement

19.4  subs, split and split-lines

19.5  trim, triml, trimr, trim-newline

19.6  escape, char-name-string, char-escape-string

19.7  lower-case, upper-case, capitalize

19.8  index-of, last-index-of

19.9  blank?, ends-with?, starts-with?, includes?

sitemap