I want help with a regex string. A number should always start with 260 and after that checks the numbers after 260 should either 97 or 77. I have never done regex…still new in programming…example
26097 true
26077 true
25555 false
26055 false
1 Like
iex(1)> Regex.match?(~r/^260(97|77)$/, "26097")
true
iex(2)> Regex.match?(~r/^260(97|77)$/, "26077")
true
iex(3)> Regex.match?(~r/^260(97|77)$/, "26088")
false
iex(4)> Regex.match?(~r/^260(97|77)$/, "96088")
false
Edit: Sorry for my first wrong post. I was so confident about my regex skills that I doesn’t look at the output.
1 Like
Here is a playground with your sample data so you can learn more:
@Marcus you need to use parenthesis to list alternate branches with |
iex(1)> Regex.match?(~r/^260[97|77]$/, "26097")
false
iex(2)> Regex.match?(~r/^260(97|77)$/, "26097")
true
5 Likes
If is to only do this you don’t need regex, instead you leverage Elixir pattern matching on bynaries:
defmodule BinaryString do
require Logger
def parse("260" <> number_ends), do: _parse(number_ends)
def parse(number), do: Logger.info("Number #{number} doesn't start with 260.")
defp _parse(number_ends) when number_ends in ["97", "77"] do
Logger.info("Number end match for: #{number_ends}") # should log 97 or 77
end
defp _parse(number_ends) do
Logger.info("Number #{number_ends} doesn't end in 97 or 77.")
end
end
This may still be improved, but I think It’s enough to show the concept.
3 Likes
Patern matching does the trick.
fun = fn
(<<"260", x, "7">>) when x in [?7, ?9] -> true
_ -> false
end
iex(9)> fun.("26097")
true
iex(11)> fun.("26077")
true
iex(13)> fun.("260771")
false
Since there are two different possible values, you can pattern match directly on the string in two different clauses.
I don’t know if it defeats the purpose of your question, but here it goes
fun = fn
"26097" -> true
"26077" -> true
_ -> false
end
4 Likes