有没有什么办法让字符串包含/正则表达式在参数匹配? 例如,字符串是“发生了一些错误”。但我希望它匹配子字符串“发生错误”。我试过,但它不工作:与字符串的Elixir方法模式匹配包含
defp status({:error, ~r/error happened/}, state) do
end
有没有什么办法让字符串包含/正则表达式在参数匹配? 例如,字符串是“发生了一些错误”。但我希望它匹配子字符串“发生错误”。我试过,但它不工作:与字符串的Elixir方法模式匹配包含
defp status({:error, ~r/error happened/}, state) do
end
没有,既不字符串包含也不正则表达式匹配可使用两种模式匹配或保护功能来完成。你最好的选择是在模式中匹配{:error, error}
,并在函数内部使用例如字符串进行字符串匹配。 cond
:
defp status({:error, error}, state) do
cond do
error =~ "error happened" -> ...
...
end
end
什么可以在模式匹配来完成是一个前缀匹配。如果这是对你不够好,你可以这样做:
defp status({:error, "error happened" <> _}, state) do
这将匹配任何字符串开头"error happened"
。
虽然@Dogbert答案是绝对正确的,还有一招时的错误信息不能超过长,比方说,140个象征一个可以使用(又名Twitter的大小错误消息。)
defmodule Test do
@pattern "error happened"
defp status({:error, @pattern <> _rest }, state),
do: IO.puts "Matched leading"
Enum.each(1..140, fn i ->
defp status({:error,
<<_ :: binary-size(unquote(i)),
unquote(@pattern) :: binary,
rest :: binary>>}, state),
do: IO.puts "Matched"
end)
Enum.each(0..140, fn i ->
defp status({:error, <<_ :: binary-size(unquote(i))>>}, state),
do: IO.puts "Unmatched"
end)
# fallback
defp status({:error, message}, state) do
cond do
message =~ "error happened" -> IO.puts "Matched >140"
true -> IO.puts "Unatched >140"
end
end
def test_status({:error, message}, state),
do: status({:error, message}, state)
end
测试:
iex|1 ▶ Test.test_status {:error, "sdf error happened sdfasdf"}, nil
Matched
iex|2 ▶ Test.test_status {:error, "sdf errors happened sdfasdf"}, nil
Unmatched
iex|3 ▶ Test.test_status {:error, "error happened sdfasdf"}, nil
Matched leading
iex|4 ▶ Test.test_status {:error,
...|4 ▷ String.duplicate(" ", 141) <> "error happened sdfasdf"}, nil
Matched >140