Regular Expressions in Elixir case

Daisuke Shimamoto picture Daisuke Shimamoto · Jan 7, 2016 · Viewed 9.3k times · Source

Can you use a Regular Expression inside a case in Elixir?

So something along the lines of this:

case some_string do
  "string"        -> # do something
  ~r/string[\d]+/ -> # do something
  _               -> # do something
end

Answer

Patrick Oscity picture Patrick Oscity · Jan 7, 2016

With case it is not possible, but you can use cond:

cond do
  some_string == "string"                     -> # do something
  String.match?(some_string, ~r/string[\d]+/) -> # do something
  true                                        -> # do something
end

The reason is that there is no way to hook into the pattern matching by calling special functions for specific values. I guess you got the idea from Ruby, which implements this by defining the special operator ===. This will be implicitly called by Ruby's case statement and for a regex it will match the given value.