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]?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With