Is there a simple way to get a string representation of a regex? Passing a regex to IO.inspect prints out the string representation so I assume this must be possible in some way.
2 Answers
You can use Regex.source/1.
Regex.source(regex)
Returns the regex source as a binary.
Demo:
iex(1)> Regex.source(~r/[a-z]/)
"[a-z]"
Comments
Acc. to Elixir Regex documentation you may use:
source(regex)
source(t) :: String.t
Returns the regex source as a binary.
opts(regex)-opts(t) :: String.t
Returns the regex options as a string.
See Elixir demo:
rx = ~r/\(cat\d{8} #{"foo"}\)/i
IO.puts Regex.opts(rx)
IO.puts Regex.source(rx)
Output:
i
\(cat\d{8} foo\)
Knowing both the pattern and modifiers, you can base your further actions.