你可以case在Elixir中使用正则表达式吗?
所以有类似的东西:
case some_string do
"string" -> # do something
~r/string[\d]+/ -> # do something
_ -> # do something
end
Run Code Online (Sandbox Code Playgroud)
Pat*_*ity 37
有了case它是不可能的,但你可以使用cond:
cond do
some_string == "string" -> # do something
String.match?(some_string, ~r/string[\d]+/) -> # do something
true -> # do something
end
Run Code Online (Sandbox Code Playgroud)
原因是没有办法通过调用特定值的特殊函数来挂钩模式匹配.我猜你从Ruby那里得到了这个想法,它通过定义特殊运算符来实现它===.这将由Ruby的case语句隐式调用,对于正则表达式,它将匹配给定的值.
Hen*_*k N 25
帕特里克在他的回答中说,没有内置的东西,这cond可能是你最好的选择.
但是要添加另一个选项并展示Elixir的灵活性:因为case只是Elixir中的一个宏,你可以实现自己的宏regex_case来做到这一点.
您应该记住,这可能会使代码更难理解项目中的新人,但如果您进行大量的正则表达式匹配,那么权衡可能是有意义的.你是法官.
我刚刚实现了这个,只是为了看到它是可能的:
defmodule RegexCase do
defmacro regex_case(string, do: lines) do
new_lines = Enum.map lines, fn ({:->, context, [[regex], result]}) ->
condition = quote do: String.match?(unquote(string), unquote(regex))
{:->, context, [[condition], result]}
end
# Base case if nothing matches; "cond" complains otherwise.
base_case = quote do: (true -> nil)
new_lines = new_lines ++ base_case
quote do
cond do
unquote(new_lines)
end
end
end
end
defmodule Run do
import RegexCase
def run do
regex_case "hello" do
~r/x/ -> IO.puts("matches x")
~r/e/ -> IO.puts("matches e")
~r/y/ -> IO.puts("matches y")
end
end
end
Run.run
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7998 次 |
| 最近记录: |