Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Split a string so it doesn't return empty strings in the list?

Tags:

elixir

I'm splitting a string on a regex. The resulting array contains empty strings where the regex matched. I don't want those. E.g.,

iex(1)> String.split("Hello world. How are you?", ~r/\W/)
["Hello", "world", "", "How", "are", "you", ""]

How can I split a string so it doesn't return empty strings in the list?

like image 736
Rodney Folz Avatar asked May 11 '16 07:05

Rodney Folz


1 Answers

As mentioned in the String.split docs,

Empty strings are only removed from the result if the trim option is set to true (default is false).

So you'll want to add that as an option in your call to String.split:

String.split("Hello world. How are you?", ~r/\W/, trim: true)
["Hello", "world", "How", "are", "you"]
like image 51
Rodney Folz Avatar answered Sep 21 '22 12:09

Rodney Folz