Trouble splitting text at newlines

I am having trouble splitting lines of text in Phoenix. If I do the following in the Phoenix shell (iex -S mix phoenix.server) all is good:

iex(22)> text = "\"
iex(23)> Regex.split( ~r/\r|\n|\r\n/, text)
["", ""]

I have similar code in my app – Regex.split( ~r/\r|\n|\r\n/, String.trim(text))
that does not split the string.

Any ideas? Going crazy on this one.

1 Like

A little off-topic, but why not String.split(text, ["\n", "\r", "\r\n"])?

It’s faster.

iex(7)> text = "\"
iex(8)> test_regex = fn ->
...(8)>   1..1_000_000 |> Enum.each(fn _ -> Regex.split(~r/\r|\n|\r\n/, text) end)
...(8)> end
#Function<20.52032458/0 in :erl_eval.expr/5>
iex(9)> test_string = fn ->
...(9)>   1..1_000_000 |> Enum.each(fn _ -> String.split(text, ["\n", "\r", "\r\n"]) end)
...(9)> end
#Function<20.52032458/0 in :erl_eval.expr/5>
iex(10)> test_regex
{12007600, :ok}
iex(11)> test_string
{6135976, :ok}
1 Like

Regex.split( ~r/\r|\n|\r\n/, String.trim(text)) should totally do the job. Please make sure, you are actually assigning the result of the operation to a variable!

If you do that already, please show a little bit more context (the complete function) and an example call that shows how the string is not split.

1 Like

Thanks, got it fixed!

1 Like

Thanks! all working now. (And I appreciate the speed)

1 Like

It’s always nice to post the actual solution after finding it.

This recapitulation does help to understand the error and to not repeat it. Also people having the same problem might discover your solution and might apply it to their problem.


In my case it was an embarrassing and non-informative mistake. Sorry!

1 Like