Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure stripMargin

Scala offers a method called stripMargin that removes the left-hand part of a multiline string up to a specified delimiter (default: "|"). Here is an example:

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

returns the string

Foo
Bar

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

Thanks.

UPDATE: The example I gave is not complete. The stripMargin method also preserves whitespace after the delimiter:

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

returns the string

Foo
   Bar
like image 983
Ralph Avatar asked Oct 06 '10 11:10

Ralph


1 Answers

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

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"
like image 70
Abhinav Sarkar Avatar answered Sep 17 '22 18:09

Abhinav Sarkar