Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why cant i split at "|" in clojure [duplicate]

Tags:

regex

clojure

I am trying to split a string in clojure "Hello|World" but when use the split method "(clojure.string/split x #"|")" I get a weird result, I get this "[h e l l o | w o r l d]". Can anyone tell me why it does this and how can I split it up to get [hello world]?

like image 427
Emma Avatar asked Mar 07 '26 14:03

Emma


1 Answers

Here is the answer:

(str/split "Hello|World" #"|")  => ["H" "e" "l" "l" "o" "|" "W" "o" "r" "l" "d"]
(str/split "Hello World" #" ")  => ["Hello" "World"]
(str/split "Hello|World" #"\|") => ["Hello" "World"]

In a regular expression, the | character is special, and needs to be escaped with a backslash \.

The | character is a logical operator in regex and is normally used to mean "or", like "abc|def":

(str/split "Hello|World" #"e|o") => ["H" "ll" "|W" "rld"]

Since you had nothing else present it seems to have been interpreted as "anything OR anything", so it matched the boundary between each character.

See the Java docs for more information.

like image 84
Alan Thompson Avatar answered Mar 10 '26 08:03

Alan Thompson