mruoss

mruoss

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"

Showing Posts 1 to 10

dimitarvp

dimitarvp

The only thing that I am aware of after 5 minutes of searching is Regex.escape/1.

And it only covers part of these: Escape characters.

adamu

adamu

Do you mean at compile-time?

You cannot do it at runtime, because once you have a string, you cannot identify how that string was produced. For example:

iex(1)> " "
" "
iex(2)> "\s"
" "
iex(3)> <<32>>
" "

Given the string " ", there’s no way to tell if the source code entered the value directly, used the escape character, or or constructed the string some other way.

mruoss

mruoss OP

Hi @adamu
I don’t mean to restore it the way it was created. I just need to restore it to one of the escape char variants.

For example I would want this:

iex> Magic.escape("\\0")
"\\0"

iex> Magic.escape(<<0>>)
"\\0"

@dimitarvp It is not exactly what I am looking for as it does a bit more.

adamu

adamu

Including for all spaces, newlines, unicode characters, and random bytes?

mruoss

mruoss OP

Excluding newlines, tabs and spaces. But others like \r, \0, \uNNNN… :wink:

The more I think about it, the more I get the feeling that it is not possible…

adamu

adamu

\r is carriage return, you probably want to skip that too. \uNNNN is all Unicode characters, so literally everything that’s valid Unicode would be converted to that.

I think the problem is that what you are asking for doesn’t make sense. :slight_smile: What are you trying to do?

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

mruoss OP

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

Eiji

Enum.reject(0x00..0x1F, & &1 in '\n\t')
https://github.com/rrrene/elixir-style-guide

adamu

adamu

What are you trying to do with that information?

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews