Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pattern matching Elixir方法与字符串包含的模式匹配_Pattern Matching_Elixir - Fatal编程技术网

Pattern matching Elixir方法与字符串包含的模式匹配

Pattern matching Elixir方法与字符串包含的模式匹配,pattern-matching,elixir,Pattern Matching,Elixir,有没有办法让参数匹配中的字符串包含/regex? 例如,字符串是“发生了一些错误”。但我希望它与子字符串“error acevent”匹配。我尝试过这个,但不起作用: defp status({:error, ~r/error happened/}, state) do end 否,不能使用模式匹配或保护函数进行字符串包含或正则表达式匹配。您最好匹配模式中的{:error,error},并使用例如cond在函数内部进行字符串匹配: defp status({:error, error

有没有办法让参数匹配中的字符串包含/regex? 例如,字符串是“发生了一些错误”。但我希望它与子字符串“error acevent”匹配。我尝试过这个,但不起作用:

  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
defp状态({:error,“error-ocated”{},state)do

这将匹配任何以
“error ocated”

开头的字符串。尽管@Dogbert的答案绝对正确,但当错误消息长度不能超过140个符号(即推特大小的错误消息)时,可以使用一种技巧

defmoduletestdo
@“发生错误”模式
defp状态({:error,@pattern_rest},state),
do:IO.puts“匹配的前导”
每个枚举(1..140,fn i->
defp状态({:错误,
},陈述),
do:IO.puts“匹配”
(完)
每个枚举(0..140,fn i->
defp状态({:错误,},状态),
do:IO.puts“不匹配”
(完)
#退路
defp状态({:错误,消息},状态)do
康多
消息=~“发生错误”->IO.puts“匹配>140”
true->IO.puts“未连接>140”
结束
结束
def测试_状态({:错误,消息},状态),
do:状态({:错误,消息},状态)
结束
测试:

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
iex | 1▶ Test.Test_状态{:错误,“sdf错误发生sdfasdf”},无
匹配
iex | 2▶ Test.Test_状态{:错误,“sdf错误发生sdfasdf”},无
无与伦比的
iex | 3▶ Test.Test_状态{:错误,“错误发生sdfasdf”},无
匹配前导
iex | 4▶ Test.Test_状态{:错误,
...|4 ▷    String.duplicate(“,141)”发生错误sdfasdf“},无
匹配>140
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