Thanks, @NobbZ! I think I see what you mean by “replacement language”. This seems to be a special case when a regex is passed as the pattern to replace/4, as illustrated below:
$ iex
Erlang/OTP 22 [erts-10.4] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]
Interactive Elixir (1.9.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> "abc" |> String.replace("a", "z\\0") |> IO.puts()
z\0bc
:ok
iex(2)> "abc" |> String.replace(~r/a/, "z\\0") |> IO.puts()
zabc
:ok
iex(3)> "abc" |> String.replace("a", "\\") |> IO.puts()
\bc
:ok
iex(4)> "abc" |> String.replace("a", "\\\\") |> IO.puts()
\\bc
:ok
iex(5)> "abc" |> String.replace(~r/a/, "\\") |> IO.puts()
\bc
:ok
iex(6)> "abc" |> String.replace(~r/a/, "\\\\") |> IO.puts()
\bc
:ok
Is this behavior documented anywhere? I know the docs mention using “\1”, etc. to do capture substitution, and that implies that \ is being treated specially, but I’m still surprised that even without capture replacement regex patterns cause replacements to behave differently.
Edit: For a simple regexes, one can avoid the replacement language by either 1) supplying a list of strings as the pattern argument, or a function as the replacement argument.






















