Pattern matching at the end of a string / binary argument

I am currently writing a little test leader at Elixir. I want to use pattern matching to evaluate if a file is in specification format (ends with "_spec.exs"). There are many guides on how to map a pattern at the beginning of a line, but something will not work with line endings:

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

This always ends with a compilation error:

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

Is there any solution for this?

+6
source share
4 answers

Looking at the link in the Elixir Getting Started Guide seems like this is not possible. The relevant section says:

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

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

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

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

Since strings are binaries under the hood in Elixir, matching suffix should be impossible for them.

+6
source

using the more traditional pattern matching definition:

 String.match?(filename, ~r"_spec\.exs$") 
+4
source

As the other answers said, in elixir / erlang this is not possible. Another solution, however, is to approach the problem using the Path module, so for your use case you should do something like the following:

 dir_path |> Path.join( "**/*_spec.exs" ) |> Path.wildcard 
+1
source

Check compliance:

 String.ends_with? filename, "_spec.exs" 

Extract file:

 file = String.trim_trailing filename, "_spec.exs" 
+1
source

All Articles