mruoss

mruoss

Is there a way to escape escape characters i.e. turn `"\u2003"` => `"\\u2003"`?

Hey, does anybody know if it is possible to escape escape characters like \r or \u2003? Given a string containing such characters, I’d like to turn them into an escaped form as follows:

iex> Magic.escape("\r\u2003")
"\\r\\u2003"

Most Liked

Eiji

Eiji

All you need to do is to define a list of characters you want to escape and the rest is a simple reduce:

defmodule Example do
  @characters_to_escape [?b]

  def sample(string) when is_binary(string) do
    for <<char::utf8 <- string>>, reduce: "" do
      acc -> acc <> maybe_escape(char)
    end
  end

  defp maybe_escape(char) when char in @characters_to_escape do
    char
    |> Integer.to_string(16)
    |> String.pad_leading(4, "0")
    |> then(&"\\u" <> &1)
  end

  defp maybe_escape(char), do: <<char::utf8>>
end

iex> Example.sample("a b c")
"a \\u0062 c"
Eiji

Eiji

Enum.reject(0x00..0x1F, & &1 in '\n\t')

mruoss

mruoss

Thank you all for the input and the sparring. @Eiji I guess I was hoping for some well-defined distinction / function to tell “printable” from other unicode chars. But I learned that what needs to be escaped depends very much on the use case. Looking at Jason, there is the :escape option which can be one of 4 possible values, each one escaping more or fewer chars.

I think the problem is that what you are asking for doesn’t make sense.

@adamu Yes, that too, probably! :smiley:

Inspired by Jason I ended up with something like the following which works for my case for now (probably needs refinement):

defmodule NotSoMuchMagic do
  @escape_chars '\b\f\r\v\"\\'
  @escape_char_maping Enum.zip('\b\f\r\v\"\\', 'bfrv"\\')
  @unicode_char_mapping 0x00..0x1F |> Enum.reject(&Kernel.in(&1, '\n\t'))

  for {src, dst} <- @escape_char_maping do
    defp encode_char(unquote(src)), do: [?\\, unquote(dst)]
  end

  for uchar <- @unicode_char_mapping do
    unicode_sequence = List.to_string(:io_lib.format("\\u~4.16.0B", [uchar]))
    defp encode_char(unquote(uchar)), do: unquote(unicode_sequence)
  end

  defp encode_char(char), do: char

  def encode(binary) do
    iodata = for (<< char::utf8 <- binary >>), do: encode_char(char)
    IO.iodata_to_binary(iodata)
  end
end
iex> NotSoMuchMagic.encode("\r \t \v \0 \u0028 \u0012")
"\\r \t \\v \\u0000 ( \\u0012"
mruoss

mruoss

Decide how to encode them. :wink:

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

YAML - Wikipedia.

If you want to produce “ascii only” yaml and escape everything else that’s fine, but it seems like yaml technically supports the full UTF8 spectrum. My overall point is that I would pick a well known subset of UTF8 like ASCII and then build your filter on top of that. All ASCII chars go in as is, non ascii are use the escaped utf8 form.

Where Next?

Popular in Questions Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

We're in Beta

About us Mission Statement