Jiacai Liu
Jiacai Liu

Reputation: 2741

how to split by period in clojure

> (clojure.string/split "clojure.org" #"\\.")

["clojure.org"]

I have read src of split which is

(defn split
  "Splits string on a regular expression.  Optional argument limit is
  the maximum number of splits. Not lazy. Returns vector of the splits."
  {:added "1.2"}
  ([^CharSequence s ^Pattern re]
     (LazilyPersistentVector/createOwning (.split re s)))
  ([ ^CharSequence s ^Pattern re limit]
     (LazilyPersistentVector/createOwning (.split re s limit))))

It calls Pattern.split inside. The strange thing is following codes work while Clojure doesn't

Pattern p = Pattern.compile("\\.");
System.out.println(Arrays.toString(p.split("clojure.org")));

# output
[clojure, org]

Did I missing something?

Upvotes: 2

Views: 780

Answers (1)

ntalbs
ntalbs

Reputation: 29458

Pattern p = Pattern.compile("\\.");

In Java, "\\." is a normal string. So you have to escape backslash itself in order to represent \ in the regular expression.

user=> (clojure.string/split "clojure.org" #"\.")
["clojure" "org"]

In Clojure, #"\." is regular expression. Backslashes in the pattern are treated as themselves (and do not need to be escaped with an additional backslash)

The following webpage will be helpful. (Find "regex patterns" in the page)

http://clojure.org/reference/reader

Upvotes: 8

Related Questions