Pattern match a string in a map for searching

Hi friends,
I wonder is there any way to search in a map like this:

%{
  "CoinWithName" => 1,
  "CoinWithId" => 2,
  "CancelOperation" => 3,
  "CoinID:" <> id => id
}["CoinID:25"]

I can use a function like this, but if top way works, my code is going to be Beautiful and clear.

defmodule MatchStick do
  def doMatch("CoinID:" <> rest), do: IO.inspect(rest)
  def doMatch(_) do 0 end
end

MatchStick.doMatch("CoinID:25")

Thank you

That is not valid value for a map.

It’s possible to match map keys, with something like String.starts_with?

But it is not clear what You really want to do.

hmm… nothing to match against the pattern.

At least I would thing of something like do_match(map, pattern). I don’t use JS convention for my function name… doMatch => do_match.

1 Like

I just hoped to find a way like the first map I sent,

  def user_message("CoinID:" <> coin_id), do: coin_id

  def user_message(message) do
    # TODO: it should be changed with Gettext
    %{
      "CoinWithName" => 1,
      "CoinWithId" => 2,
      "CancelOperation" => 3
    }[message]
  end

But I did like this

Yeah, sorry, I just copy and paste it

I don’t understand your code… in particular, I don’t know what the input is, and what the expected output should be.

You input a binary, then You get :ok, or 0, or You use a hard-coded map inside the function?!

Maybe You can express what You really want to do, in words.

1 Like

Is this what you want?

map  = 
%{
  "CoinWithName" => 1,
  "CoinWithId" => 2,
  "CancelOperation" => 3,
  "CoinID:1" => 1,
  "CoinID:10" => 10,
  "CoinID:25" => 25,
  "CoinID:100" => 100,
}

case Map.get(map, "CoinID:25", :error) do
  :error -> :error
  value -> {:ok, value}
end
#=> {:ok, 25}

Which is pretty much the same as Map.get(map, "CoinID:25", :error) or Map.fetch(map, "CoinID:25"), but I just put it like that if the ConID:XX differs from the value in the map, you can pattern match and return something else.

Hi my friend,
As I said, I just wanted to know is there a way the code works or not

%{
  "CoinWithName" => 1,
  "CoinWithId" => 2,
  "CancelOperation" => 3,
  "CoinID:" <> id => id
}["CoinID:25"]

I can not use your code because I do not know what is the input

This part is always fixed and the answer is decisive

  def user_message(message) do
    # TODO: it should be changed with Gettext
    %{
      "CoinWithName" => 1,
      "CoinWithId" => 2,
      "CancelOperation" => 3
    }[message]
  end

‌But the another part is not, just the string Coind: is always fixed.

But thank you for your suggestion I have no problem I am just curious the first code can be changed and work or not.

Hi !
I am still unable to understand what you need.
If you could please provide valid input for your function, and what is the expected return value, I am sure people here could help you.
Pretty much write a test for ExUnit.