Pattern matching a string and getting matched values as string

I’m trying to pattern match the string
"P11W3"

I need to get both the numbers after the “P” and the “W” as their string representation. So I did some pattern matching

"P" <> <<a::16>> <> "W" <<b::8>> = "P11W3"

However, I’m struggling to get the value “11” from variable a.

If I print <<a>> I get just “1”.
if I print a I get 12593

How can I properly convert the matched value to a string?

1 Like

Could I suggest that pattern matching is the wrong tool for the job here? Why not try the Regex module from the Standard Library. For example:

iex(30)> Regex.compile!("P(?<first_number>[0-9]+)W(?<second_number>[0-9]+)") |>
 Regex.named_captures("P11W3")
%{
  "first_number" => "11",
  "second_number" => "3"
}
iex(31)> 

…but for the sake of the argument, this works:

iex(38)> "P" <> <<a::bytes-size(2)>> <> "W" <> b = "P11W3"
"P11W3"
iex(39)> a
"11"
iex(40)> b
"3"
iex(41)> 

But of course it will only work for two-digit numbers.
Suggested further reading: Pattern-matching complex strings – The Pug Automatic

—EDIT—
Why didn’t the OP’s code work? Here are some hints. Hint 1:

iex(63)> "P" <> <<a::16>> <> "W" <> <<b::8>> = "P11W3"
"P11W3"
iex(64)> a
12593
iex(65)> b
51
iex(66)> <<a>>
"1"
iex(67)> <<a::16>>
"11"
iex(68)> b
51
iex(69)> a  
12593
iex(70)> <<b>>
"3"
iex(71)> <<b::8>>
"3"
iex(72)> 

Hint 2:
12 593 (base 10) = 00110001 00110001 (binary) = 49 49 = “11” (ASCII)
51 (base 10) = 00110011 (binary) = 51 = “3” (ASCII)

See here: Bitstring and binary and here: Kernel.SpecialForms — Elixir v1.15.5

3 Likes
iex(6)> <<"P", x :: binary-size(2), "W", y :: binary-size(1)>> = "P11W3"
"P11W3"
iex(7)> x
"11"
iex(8)> y
"3"

Don’t forget to mark the solution

3 Likes
iex(1)> "P" <> <<a::16>> <> "W" <> <<b::8>> = "P11W3"
"P11W3"
iex(2)> <<a::16>>
"11"
iex(3)> <<b::8>>
"3"
iex(4)>
1 Like