8
votes

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?

1

1 Answers

17
votes

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"]