aifrak
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})
Marked As Solved
Also Liked
kip
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.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









