1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Splitting On Whitespace as a clojure til.

This commit is contained in:
jbranchaud
2015-03-29 15:55:16 -05:00
parent f90bdd97c3
commit 40180d0885
2 changed files with 38 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
# Splitting On Whitespace
If you have a string with spaces and you want to split the string into a
vector of strings (delimited by the spaces), then you can do something like
this:
```clojure
(clojure.string/split "split me up" #" ")
; ["split" "me" "up"]
```
However, if you have extra spaces in your string, the output may not be quite
what you want:
```clojure
(clojure.string/split "double spacing wtf?" #" ")
; ["double" "" "spacing" "" "wtf?"]
```
A quick fix might look like this:
```clojure
(clojure.string/split "double spacing wtf?" #"[ ]+")
; ["double" "spacing" "wtf?"]
```
That's nice, but it is going to fall over as soon as we run into input with
tabs and new lines. Assuming we want to split on all whitespace, we should
tell our regular expression to do just that:
```clojure
(clojure.string/split "we\thave new\nlines and tabs\n" #"[\s]+")
; ["we" "have" "new" "lines" "and" "tabs"]
```