How to quote regular expression?

When i want to quote regular express, found these:

iex(20)> a = ~r/^\d+$/
~r/^\d+$/
iex(21)> Code.eval_quoted(quote do: "123" =~ unquote(a))    
** (CompileError) nofile: invalid quoted expression: ~r/^\d+$/
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    (stdlib) lists.erl:1355: :lists.mapfoldl/3
    (elixir) lib/code.ex:207: Code.eval_quoted/3
iex(21)> Code.eval_quoted(quote do: "123" =~ unquote({:sigil_r, [context: Elixir, import: Kernel], [{:<<>>, [], ["^\\d+$"]}, []]}))
{true, []}

why ?

Macro.escape/2 is your friend. The value returned by ~r/^\d+$/ is a %Regex{} struct and structs are not AST literals - they need to be escaped. Alternatively you could quote the regex production a = quote(do: ~r/^\d+$/), which will return valid AST as well.

1 Like

You can do it like this:

a = quote do ~r/^\d+$/ end
Code.eval_quoted(quote do: "123" =~ unquote(a))

thanks, got a better understand of AST.