Pattern Matching Strings Share Some Text

Hello all, how does one do pattern matching against strings that share some text?

e.g. both of these calls go to the same method, but the method knows if it’s foo or bar

some_function(event: "keyup_foo") 
some_function(event: "keyup_bar") 

def handle_event("keyup_[???]", payload, socket) do
  # somehow use foo or bar here
end
4 Likes

Basically:

def func("keyup_" <> key), do: #operate depending on the value of `key` here.
4 Likes

Thank you, this is very elegant!

I have no idea why this works the way it does, where do I learn more?

Or, if one needs to pattern match several parts of the known size (for something like "keyup_foo_1" vs "keyup_bar_2"):

def match(<<"keyup_", key :: binary-size(3), "_", subkey :: binary>>), do: ...
3 Likes

To learn more you can take a look a the Getting Started guide (scroll down to find a few words about pattern matching) and documentation for <<>>
edit: also documentation for <>

1 Like