有沒有什麼辦法讓字符串包含/正則表達式在參數匹配? 例如,字符串是「發生了一些錯誤」。但我希望它匹配子字符串「發生錯誤」。我試過,但它不工作:與字符串的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