Replace
We use str/replace to replace. The first parameter is the source string, the next parameter is the matching string, and the last parameter is the replacement content.
match / replacement can be:string / stringchar / charpattern / (string or function of match).
;;In the replacement string, $0, $1, and so on are used to reference the group that matches the string.(Str/replace "@ David graeber 12.3%, @ shanley 19.8%" # "(@ \ S +) \ s ([. 0-9] +) % "" $2 ($1 )");=> "12.3 (@ David graeber), 19.8 (@ shanley )";;Use functions to replace strings for greater flexibility(Println (str/replace "@ David graeber 12.3%, @ shanley 19.8%" # "(@ \ w +) \ s ([. 0-9] +) % ,? "(Fn [[_ person percent] (let [points (-> percent Float/parseFloat (* 100) Math/round)] (str person "'s followers grew" points "points. \ n ")))));Print => @ David graeber's followers grew 1230 points.;Print => @ shanley's followers grew 1980 points.;Print =>
Context-independent syntax
Compared with regular expressions, context-independent Syntax provides more expressive matching methods. You can use nested expressions to express your thoughts.
We will use Instapares in JSON syntax. (This example is not strictly tested and has no special features. If you want to apply it to actual development, use data. json)
;;Project. clj in your project must contain the following dependencies (you may need to restart JVM);;: Dependencies [[instaparse "1.2.4"];;;;Assume that your ns macro contains the following content:;;(: Require [instaparse. core: as insta]);;Or you load the following in REPL:;;(Require '[instaparse. core: as insta])(Def barely-tested-json-parser (insta/parser "object = <'{'>
(Members
) * <'}'>
= Pair (
<','>
Members )*
= String
<':'>
Value
= String | number | object | array | 'true' | 'false' | 'null' array = <'['> elements * <']'>
= Value
(<','>
Elements) * number = int frac? Exp?
= '-'? Digits
= '.' Digits
= E digits
= ('E' | 'E') (<'+'> | '-')?
= # '[0-9] +' (* First sketched state machine; then it was easier to figure out regex syntax and all the maddening escape-backslashes. *) string = <'\\\ "'> # '([^ \" \\\] | \\\\.) * '<' \ "'>
= # '\ S +' ") (barely-tested-json-parser" {\ "foo \": {\ "bar \": 99.9e-9, \ "quux \": [1, 2,-3]} ")
;
=> [: Object
;
[: String "foo"]
;
[: Object
;
[: String "bar"]
;
[: Number "99" "." 9 "" e ""-"9"]
;
[: String "quux"]
;
[: Array [: number "1"] [: number "2"] [: number "-" "3"]
;;
The final output is a bit cool. Let's improve it.(-> (Barely-tested-json-parser "{\" foo \ ": {\" bar \ ": 99.9e-9, \" quux \ ": [1, 2,-3] }}") (insta/transform {: object hash-map: string str: array vector: number (comp edn/read-string str )}))
;
==>{ "Foo" {"quux" [1 2-3], "bar" 9.99E-8 }}
;;
All the content is on it.
;;
;;
= The syntax on the right is mainly used to hide unnecessary information. For example, we do not care about spaces, so we set
To hide
;;
;;
= The syntax on the left is only used to avoid nested output. For example, "members" is only a set object,
;;
So we stopped this meaningless nested relationship.
Construct complex string redirection
With-out-str provides a simple method to construct strings. it redirects the standard output (out) to StringWriter and returns the result string. in this way, you can use functions such as print to obtain strings (even in nested functions)
(let [shrimp-varieties ["shrimp-kabobs" "shrimp creole" "shrimp gumbo"]] (with-out-str (print "We have ") (doseq [name (str/join ", " shrimp-varieties)] (print name)) (print "...")));=> "We have shrimp-kabobs, shrimp creole, shrimp gumbo..."
Format a string
Java templates help you easily construct strings. Reference
;;% S is often used as the print parameter. % needs to use %(Format "% s enjoyed % s %." "Your ambique" 19.8);=> "Maid 19.8% .";;1 $ prefix can be referenced to the first parameter(Format "% 1 $ tY-% 1 $ tm-% 1 $ latex td" # inst "2000-01-02T00: 00: 00 ");=> "2000-01-02";;Parameters following the prefix of 1 $ and 2 $ can be referenced.(Format "New year: % 2 $ tY. Old year: % 1 $ tY" # inst "2000-01-02T00: 00: 00" # inst "3111-12-31T00: 00: 00 ");=> "New year: 3111. Old year: 2000"
CL-Format
Cl-format is a notorious feature in Common Lisp. for example, you can construct a string from a sequence (the odd degree is like representing a number in English and using two types of Roman numerals ). however, the reference to the printed date and the above unordered parameters is weaker than the common Formatting Function.
You only need to remember that cl-format is a language that nobody cares about. But if you like it and want to learn it, read the Practical Common Lisp tutorial. Or the Common Lisp manual.
;; The first param prints to *out* if true. To string if false.;; To a stream if it's a stream.(pp/cl-format true "~{~{~a had ~s percentage point~:p.~}~^~%~}" {"@davidgraeber" 12.3 "@shanley" 19.8 "@tjgabbour" 1});print=> @davidgraeber had 12.3 percentage points.;print=> @tjgabbour had 1 percentage point.;print=> @shanley had 19.8 percentage points.(def format-string "~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~}")(pp/cl-format nil format-string []);=> ""(pp/cl-format nil format-string ["@shanley"]);=> "@shanley"(pp/cl-format nil format-string ["@shanley", "@davidgraeber"]);=> "@shanley and @davidgraeber"(pp/cl-format nil format-string ["@shanley", "@davidgraeber", "@sarahkendzior"]);=> "@shanley, @davidgraeber, and @sarahkendzior"
Contributor
Tj Gabbour tjg@simplevalue.de, 2013 (original author)