2015-09-08 61 views
6

我目前正在Elixir寫一個小測試跑步者。我想使用模式匹配來評估文件是否處於規格格式(以「_spec.exs」結尾)。上有許多教程如何在一個字符串的開頭模式匹配,但是,不知怎的,不會對字符串的結尾工作:字符串/二進制參數結尾的模式匹配

== 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 

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

defp run_spec(file) do 
    ... 
end 

這總是在編譯錯誤結束有沒有解決方案?

回答

6

在Elixir入門指南中看到這個link,看起來這是不可能的。相關部分規定:

However, we can match on the rest of the binary modifier:

iex> <<0, 1, x :: binary>> = <<0, 1, 2, 3>> 
<<0, 1, 2, 3>> 
iex> x 
<<2, 3>> 

The pattern above only works if the binary is at the end of <<>> . Similar results can be achieved with the string concatenation operator <>

iex> "he" <> rest = "hello" 
"hello" 
iex> rest 
"llo" 

由於字符串在藥劑在引擎蓋下的二進制文件,匹配的後綴應該是不可能了他們。

+3

是的,你是對的。這不可能。 –

1

正如其他答案所述,這是不可能在elixir/erlang。然而,另一種解決方案是使用路徑模塊來解決這個問題,以便爲您的使用情況下,你應該能夠做到像下面這樣:使用「模式匹配」更傳統的定義

dir_path 
    |> Path.join("**/*_spec.exs") 
    |> Path.wildcard 
4

String.match?(filename, ~r"_spec\.exs$") 
1

檢查匹配:

String.ends_with? filename, "_spec.exs" 

提取文件:

file = String.trim_trailing filename, "_spec.exs" 
相關問題