Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can pattern matching be done on text?

Tags:

elixir

Lets say that I want to pattern match against text. Specifically, I want to pattern match on the first letter.

For example, how do I create a pattern that would match "about" and "analog" but not "beta"?

I've tried this:

defmodule MatchStick do     def doMatch([head | tail]) when head == "a" do 1 end     def doMatch([head | tail]) do 0 end end  res = MatchStick.doMatch("abcd"); 

I've also tried character lists:

defmodule MatchStick do     def doMatch([head | tail]) when head == 'a' do 1 end     def doMatch([head | tail]) do 0 end end  res = MatchStick.doMatch('abcd'); 

Neither worked. What is the proper way to match text?

like image 857
epotter Avatar asked Sep 17 '14 17:09

epotter


1 Answers

defmodule MatchStick do   def doMatch("a" <> rest) do 1 end   def doMatch(_) do 0 end end 

You need to use the string concatenation operator seen here

Example:

iex> "he" <> rest = "hello" "hello" iex> rest "llo" 
like image 125
Kyle Avatar answered Sep 26 '22 02:09

Kyle