Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split a string in clojure not in regular expression mode

Tags:

clojure

The split in both clojure and java takes regular expression as parameter to split. But I just want to use normal char to split. The char passed in could be "|", ","," " etc. how to split a line by that char?

I need some function like (split string a-char). And this function will be called at very high frequency, so need good performance. Any good solution.

like image 407
Daniel Wu Avatar asked Jan 08 '23 23:01

Daniel Wu


1 Answers

There are a few features in java.util.regex.Pattern class that support treating strings as literal regular expressions. This is useful for cases such as these. @cgrand already alluded to (Pattern/quote s) in a comment to another answer. One more such feature is the LITERAL flag (documented here). It can be used when compiling literal regular expression patterns. Remember that #"foo" in Clojure is essentially syntax sugar for (Pattern/compile "foo"). Putting it all together we have:

(import 'java.util.regex.Pattern)
(clojure.string/split "foo[]bar" (Pattern/compile "[]" Pattern/LITERAL))
;; ["foo" "bar"]
like image 149
ez121sl Avatar answered Apr 17 '23 14:04

ez121sl