Clojure stripMargin

Scala offers the strMargin method, which removes the left side of a multiline string to the specified delimiter (default: "|"). Here is an example:

"""|Foo
   |Bar""".stripMargin

returns a string

Foo
Bar

Is there a similar feature in Clojure? If not, how would you implement it (most functionally)?

Thank.

UPDATE . The example I gave is not complete. The stripMargin method also stores spaces after the separator:

"""|Foo
   |   Bar""".stripMargin

returns a string

Foo
   Bar
+5
source share
4 answers

There is no such built-in function, but you easily write it:

user=> (use '[clojure.contrib.string :only (join, split-lines, ltrim)]) //'
nil
user=> (->> "|Foo\n  |Bar" split-lines (map ltrim) 
  (map #(.replaceFirst % "\\|" "")) (join "\n"))
"Foo\nBar"
+4
source

Google , . , .

(use '[clojure.contrib.str-utils :only (re-split re-sub str-join)])

(defn strip-margin [s]
  (let [lines (seq (re-split #"\n" s))]
    (str-join "\n"
      (for [line lines]
        (re-sub #"^\s*\|" "" line)))))
+2

Here is my complete solution compiled from the answers above:

(use '[clojure.contrib.string :only (join, split-lines, ltrim)])

(defn strip-margin
  ([s d] (->> s split-lines (map ltrim) (map #(.replaceFirst % d "")) (join "\n")))
  ([s] (strip-margin s "\\|")))

Here are a few "real" input and output samples:

(println
  (strip-margin "|<?xml version='1.0' encoding='utf-8'?>
                 |<people>
                 |  <person>
                 |    <name>Joe Smith</name>
                 |  </person>
                 |</people>"))

==>

<?xml version='1.0' encoding='utf-8'?>
<people>
  <person>
    <name>Joe Smith</name>
  </person>
</people>
nil

Thanks to all the participants.

+2
source

You can also do this with a single regex:

(use '[clojure.contrib.string :only (replace-re)])

(def test-string 
"|<?xml version='1.0' encoding='utf-8'?>
                 |<people>
                 |  <person>
                 |    <name>Joe Smith</name>
                 |  </person>
                 |</people>")


(replace-re #"(^\|)|(.+\|)" "" test-string))
+1
source

All Articles