DimWell
How do I pattern match part of string as bitstrings?
Hello Experts,
Could you please advise what would be the way to match the bitstring ?
Lets say I have and input and I want to pattern part of it as bitstsing:
@input <<116, 114, 117, 101, 32, 105, 115, 32, 110, 111, 116, 32, 102, 97, 108, 115, 101>>
@true_ <<116, 114, 117, 101>>
@false_ <<102, 97, 108, 115, 101>>
def match_bitsting( <<true_ ::size(32) , rest :: bitstring>>= input) when trues_ == @true_ do
IO.puts "I got: true"
end
def match_bitsting( <<false_ ::size(40) , rest :: bitstring>>= input) when trues_ == @false_ do
IO.puts "I got: false"
end
How should I rewrite @true_ | @false_ or the pattern matching to make it work ?
Marked As Solved
idi527
@input <<116, 114, 117, 101, 32, 105, 115, 32, 110, 111, 116, 32, 102, 97, 108, 115, 101>>
@true_ <<116, 114, 117, 101>>
@false_ <<102, 97, 108, 115, 101>>
def match_bitsting(<<@true_, rest::bits>>) do # bits is an alias for bitstring
IO.puts "I got: true"
match_continue(rest, true)
end
def match_bitsting(<<@false_, rest::bits>>) do
IO.puts "I got: false"
match_continue(rest, false)
end
Would this work for you?
Why are you using bitstrings anyway? What you have in @input is a (printable) binary.
Also Liked
NobbZ
If it is streamed data you will probably get your chunks at byte boundary (as this is the level at which your interface transfers the data) and unless the protocol specifies something that is not aligned at byte boundaries, you can safely assume binary.
BUT If the data is streamed in, you can’t safely use binary pattern matching at all but need to use a different mean of parsing/deserializing the incomming data.
What happens if your current chunk is "tru"? This does not match "true", but might after the next chunk has been received.
hugolnx
grych
If I understood the problem properly, you want to match the beginning of the input string? In this case, it is easy:
def match_bitstring("true" <> _rest), do: IO.puts("true")
def match_bitstring("false" <> _rest), do: IO.puts("false")
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









