How to remove ANSI escape sequences from a string?

What is the best way to strip ANSI escape sequences from a string?

Go from:

# Go from
"[\e[32m\"one\"\e[0m, \e[32m\"two\"\e[0m, \e[32m\"three\"\e[0m]"

# To
["one", "two", "three"]

Thanks a million!

You can use a Regex
I just grabbed one online and used it. Not really good with Regexes so not sure how efficient this is.

defmodule MyAnsi do
  @ansi_regex ~r/(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]/
  @non_alpha_regex ~r/[^0-9a-zA-Z]/

  def strip_ansi(ansi_string) when is_binary(ansi_string) do
    Regex.replace(@ansi_regex, ansi_string, "")
    |> String.split(",")
    |> Enum.map(&Regex.replace(@non_alpha_regex, &1, ""))
  end

end
1 Like

Would produce a very expected output for all the people of the world that don’t use 7-bit ASCII scripts.

4 Likes

Did you mean to say unexpected?

As a side-note I half (but probably less) implemented an ANSI parser, but ultimately changed the program output I was consuming to be most Lynn plain text. There’s quite a number of potential ANSI codes that you’d have to deal with for an accurate parser.

1 Like

Good catch! Yes, unexpected!

I read the ECMA-48 spec and yes, quite a lot more complex than just colour code!

2 Likes

Thanks a million, works like a charm! :slightly_smiling_face:

1 Like