Is it normal that `Regex.compile/2` does not print regex modifiers when atoms are passed in `options`?

Hello,

I have a question regarding the result returns by Regex.compile/2 and Regex.compile!/2.

The Elixir documentation for Regex.compile/2 and Regex.compile!/2 mentions that the second argument is binary() | [term()].

It means modifiers can be added this way:

iex)> {:ok, regex} = Regex.compile("foo", "i")
{:ok, ~r/foo/i}
iex> String.match?("FOO", regex)             
true

But I saw a solution from exercism where regex modifiers can also be added this way:

iex> {:ok, regex} = Regex.compile("foo", [:caseless])
{:ok, ~r/foo/}
iex> String.match?("FOO", regex)                     
true

In the second code snippet, is it normal that the regex is printed without any regex modifiers? ({:ok, ~r/foo/} instead of {:ok, ~r/foo/i})

1 Like

If you examine the Regex struct for these two examples you see:

iex(1)> IO.inspect Regex.compile!("foo", "i"), structs: false                          
%{
  __struct__: Regex,
  opts: "i",
  re_pattern: {:re_pattern, 0, 0, 0,
   <<69, 82, 67, 80, 77, 0, 0, 0, 1, 0, 0, 0, 241, 0, 0, 0, 255, 255, 255, 255,
     255, 255, 255, 255, 102, 0, 111, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0,
     0, ...>>},
  re_version: {"8.44 2020-02-12", :little},
  source: "foo"
}
~r/foo/i
iex(2)> IO.inspect Regex.compile!("foo", [:caseless]), structs: false
%{
  __struct__: Regex,
  opts: "",
  re_pattern: {:re_pattern, 0, 0, 0,
   <<69, 82, 67, 80, 77, 0, 0, 0, 1, 0, 0, 0, 241, 0, 0, 0, 255, 255, 255, 255,
     255, 255, 255, 255, 102, 0, 111, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0,
     0, ...>>},
  re_version: {"8.44 2020-02-12", :little},
  source: "foo"
}
~r/foo/

And its the :opts field that is used for the Inspect protocol to present the regex.

The reason you don’t see the flags in the second example is that Regex.compile/2 will call Regex.translate_options/2 to translate the string options to the list form. But there is no function to translate them back to the string form, and its the string form that is used for display purposes.

2 Likes

seems like that particular compile function ought to doc_opts given list options, no?

After checking the answers from @kip and @czrpb, I looked at the code on the main branch and I have noticed that @sabiwara made a PR related to my post.

@kip, @czrpb and @sabiwara, thank you!

4 Likes