11

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 Answer 1

20

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"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.