19 Strings and Regular Expressions

 

One of the most common programming tasks is handling strings. Java provides an immutable java.lang.String type with a rich API which has been battle tested over many years of enterprise application development. Apart from a few functions in clojure.core and a dedicated clojure.string namespace, Clojure builds on top of this robust foundations:

(class "I'm a Clojure string") ; #1
;; java.lang.String

Another common feature found in programming languages is the presence of facilities for regular expressions. A "regex" is a string which defines a search pattern for other strings. Clojure uses the same Java regular expression abstraction while offering specialized functions including a pattern match syntax literal:

(class #"I'm a pattern match string") ; #1
;; java.util.regex.Pattern

String support and regular expression functions are the topic of this chapter.

19.1  str

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

(str "This " 'is \space 1 " sentence") ; #1
;; "This is 1 sentence"

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. The default string conversion only contains the class of the object and a hexadecimal id. Sometimes this behavior is not desirable, as in the case of this lazy sequence we would like to print on screen:

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?

19.10  re-pattern, re-matcher, re-groups, re-seq, re-matches, re-find

19.11  Summary

sitemap