Clojure topic: string processing

Source: Internet
Author: User

  • This article is translated from Strings
  • This article includes operations on strings using built-in Clojure functions and standard libraries, as well as related operations in JDK.
  • Copyright: This work is licensed under a Creative Commons Attribution 3.0 Unported License (including images & stylesheets ).
  • The source code is on Github.


    Directory
    • 1 Overview
    • 2. Prerequisites
    • 3 Method
      • 3.1 Basic Methods
      • 3.2 parse complex strings
        • 3.2.1 Regular Expression
        • 3.2.2 context-independent syntax
        • 3.3 construct complex strings
          • 3.3.1 redirection
          • 3.3.2 format a string
          • 3.3.3 CL-Format
          • 4 contributor Overview
            • The string in Clojure is a Java string. You can use the corresponding method in Java to process it.
            • Java strings are immutable, so they can be conveniently used in Clojure.
            • You cannot add metadata to Java strings.
            • Clojure provides some convenient symbols


              "Foo" java. lang. string # "\ d" java. util. regex. pattern (Regular Expression, matching a number) \ f java. lang. character ('F ')

              • Note: There is a big difference between human brains and computers. so the Java string (UTF-16 encoding) is not as good as what people think one-to-one correspondence with characters. for example, a Unicode bit cannot correspond to one of the characters we think (for example, the Korean-Korean word is composed of multiple characters .) similarly, a Unicode bit may consist of 2 UTF-16 characters.


                Prerequisites

                Some examples Use clojure. string, clojure. edn, and clojure. pprint. We assume that your ns macro already contains the following content:


                (:require [clojure.string :as str]          [clojure.edn :as edn]          [clojure.pprint :as pp])

                Or in REPL, You need to load:


                (require '[clojure.string :as str])(require '[clojure.edn :as edn])(require '[clojure.pprint :as pp])

                Basic Method


                ;;Length Calculation(Count "0123 ");=> 4(Empty? "0123 ");=> False(Empty? "");=> True(Str/blank? "");=> True;;String connection(Str "foo" "bar ");=> "Foobar"(Str/join ["0" "1" "2"]);=> "012"(Str/join "." ["0" "1" "2"]);=> "0.1.2";;Use the Java method to match.;;;;In the following cases, you should prefer to use regular expressions. For example, if you are testing, you must return-1 if the test fails.;;Or a character \ o needs to be converted to a string or number.(. IndexOf "foo" "oo ");=> 1(. IndexOf "foo" "x ");=>-1(. LastIndexOf "foo" (int \ o ));=> 2;;String Truncation(Subs "0123" 1);=> "123"(Subs "0123" 1 3);=> "12"(Str/trim "foo ");=> "Foo"(Str/triml "foo ");=> "Foo"(Str/trimr "foo ");=> "Foo";;Split string(Seq "foo ");=> (\ F \ o)(Str/split "foo/bar/quux "#"/");=> ["Foo" "bar" "quux"](Str/split "foo/bar/quux" # "/" 2);=> ["Foo" "bar/quux"](Str/split-lines "foobar ");=> ["Foo" "bar"];;Case-sensitive Conversion(Str/lower-case "fOo ");=> "Foo"(Str/upper-case "fOo ");=> "FOO"(Str/capitalize "fOo ");=> "Foo";;Conversion(Str/escape "foo | bar | quux" {\| "| "});=> "Foo | bar | quux";;Obtains the byte array of the given encoding.;;(The output may be different from the following "3c3660)(. GetBytes "foo" "UTF-8 ");=> #
                                ;;Resolved to keyword(Keyword "foo ");=>: Foo;;Resolved to numbers(Bigint "20000000000000000000000000000 ");=> 200000000000000000000000000000000n(Bigdec "20000000000000000000.00000000 ");=> 20000000000000000000.00000000 M(Integer/parseInt "2 ");=> 2(Float/parseFloat "2 ");=> 2.0;;Resolved to edn, which is a subset in Clojure form(Edn/read-string "0 xffff ");=> 65535;;Read methods in Clojure format.;;;;Security Warning: if you cannot ensure that you trust the string to be processed by 100%, Set * read-eval * to false.;;* Read-eval * From Clojure1.5 is false by default, but for security,;;When processing strings, manually set false.;;Because some operations may set it to true.(Binding [* read-eval * false] (read-string "# \" [abc] \ "");=> # "[Abc]"

                Parse complex string Regular Expressions

                Regular Expressions enhance string matching. You can repeat and match one of them, and so on.

                • Regex reference

                  Groups: when we want to match an extra substring, the group of the regular expression plays a role. in the regular expression # "(group-1) (group-2)", 0th groups are the entire matching expression. the 1st groups start from the left (START, 2nd groups start from the left and the second (start, and so on. you can also nest groups. you can also reference a group later by using $0, $1, and so on.


                  • Match


                    ;;Simple Matching(Re-find # "\ d +" "foo 123 bar ");=> "123";;What will happen when the matching fails?(Re-find # "\ d +" "foobar ");=> Nil;;Returns the First Matching content for each group.(Re-matches # "(@ \ w +) \ s ([. 0-9] +) %" "@ shanley 19.8% ");=> ["@ Shanley 19.8%" "@ shanley" "19.8"];;Returns the results of all matched groups.(Re-seq # "(@ \ w +) \ s ([. 0-9] +) %" "@ David graeber 12.3%, @ shanley 19.8% ");=> (["@ David graeber 12.3%" "@ David graeber" "12.3"];["@ Shanley 19.8%" "@ shanley" "19.8"])

                    • 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)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.