Strings
John Gabriele
2014-02
(str "a" "b" "c") ;=> "abc"
(println "a" "b" "c") ; prints "a b c"
(println \a \b \c) ; same
;; Length of string:
(count "hello") ;=> 5
;; substring
(subs "something" 2 5) ;=> "met"
(require '[clojure.string :as str])
(str/join ["a" "b" "c"]) ;=> "abc"
(str/join "-" ["a" "b" "c"]) ;=> "a-b-c"
(str/reverse "hello") ;=> "olleh"
(str/split "a11b2c3" #"\d+") ;=> ["a" "b" "c"]
(str/split-lines "a\nb\n\nc\n") ;=> ["a" "b" "" "c"]
(str/replace "score is 22" "22" "100") ;=> "score is 100"
(str/replace "score is 22" #"\d+" "100") ;=> "score is 100"
(str/replace "score is 22" #"\d+" "1$0") ;=> "score is 122"
(str/replace "score is 22" #"(\d+)" "1$0") ;=> "score is 122"
(str/replace "score is 22" #"(\d+)" "1$1") ;=> "score is 122"
(str/replace "score is 22"
#"\d+"
#(str (+ (Integer/parseInt %1)
10))) ;=> "score is 32"
(str/replace "score is 22"
#"(\d+)"
#(str (+ (Integer/parseInt (%1 0))
10))) ;=> "score is 32"
$0
matches the “whole regex match”.
Don’t confuse the regex match reference syntax (
$1
) with the function literal arg syntax (%1
).$1
is embedded in a string,%1
is bare and goes in a function literal.
%&
is, of course, only for function literals and is the list of all args passed.
When you use the regex #"(\d+)"
(with the capturing parens), for some reason, the matches that replace
stores looks like this:
(str/replace "score is 22" #"\d+" #(str %&))
"score is (\"22\")"
(str/replace "score is 22" #"(\d+)" #(str %&))
;=> "score is ([\"22\" \"22\"])"
1 Formatting
(format "aa %s" "bb") ;=> "aa bb"
(format "aa%scc" "bb") ;=> "aabbcc"
(format "%f" 1.9) ;=> "1.900000"
(format "%.2f" 1.9) ;=> "1.90"
(format "%10.2f" 1.9) ;=> " 1.90"
(format "%-10.2f" 1.9) ;=> "1.90 "
(format "%4d" 42) ;=> " 42"
(format "%-4d" 42) ;=> "42 "
(format "%04d" 42) ;=> "0042"
See the java.util.Formatter docs for more details.