字符串/二进制参数结束时的模式匹配

lei*_*ifg 9 elixir

我目前正在Elixir写一个小试飞员.我想使用模式匹配来评估文件是否是规范格式(以"_spec.exs"结尾).有很多关于如何在字符串的开头进行模式匹配的教程,但是这不知道如何在字符串结尾处起作用:

defp filter_spec(file <> "_spec.exs") do
  run_spec(file)
end

defp run_spec(file) do
  ...
end
Run Code Online (Sandbox Code Playgroud)

这总是在编译错误中结束:

== Compilation error on file lib/monitor.ex ==
** (CompileError) lib/monitor.ex:13: a binary field without size is only allowed at the end of a binary pattern
    (stdlib) lists.erl:1337: :lists.foreach/2
    (stdlib) erl_eval.erl:669: :erl_eval.do_apply/6
Run Code Online (Sandbox Code Playgroud)

那有什么解决方案吗?

mil*_*lch 8

看看Elixir入门指南中的这个链接,似乎是不可能的.相关章节指出:

但是,我们可以匹配二进制修饰符的其余部分:

iex> <<0, 1, x :: binary>> = <<0, 1, 2, 3>>
<<0, 1, 2, 3>>
iex> x
<<2, 3>>
Run Code Online (Sandbox Code Playgroud)

上面的模式只有在二进制文件结束时才有效<<>>.使用字符串连接运算符可以实现类似的结果<>

iex> "he" <> rest = "hello"
"hello"
iex> rest
"llo"
Run Code Online (Sandbox Code Playgroud)

由于字符串是Elixir引擎盖下的二进制文件,因此对它们来说也不可能匹配后缀.

  • 是的,你是对的.这不可能. (6认同)