【问题标题】:How to concat upcoming variable string until given length in pattern matching?如何在模式匹配中连接即将到来的变量字符串直到给定长度?
【发布时间】:2015-10-27 08:43:57
【问题描述】:

我从串行端口接收 rfids,我发现在这种情况下模式匹配到新行不起作用,因为在每个接收到的数据之后都是“\n”。 问题是如何连接即将到来的字符串,直到状态变量字符串等于 16 长度?我已经在 Ruby 中对其进行了测试,加入的输出字符串为"\u00027A005AFA518B\r\n\u0003",我假设匹配的字符串长度等于 16,最终我想提取所需的 rfid:7A005AFA518B。我可以用于这种模式匹配吗?

当前数据处理程序:

def handle_info({:elixir_serial, serial, data}, state) do
  [head | _tail] = String.split(data, "\r\n")
  Logger.debug "head " <> head
  Logger.debug "tail #{_tail}"
  {:noreply, [data | state]}
end

使用 rfid 卡的双重检查记录:

[debug] 7A005
[debug] tail
[debug] AFA518B
[debug] tail

[debug] 7
[debug] tail
[debug] A005AFA518B
[debug] tail

【问题讨论】:

    标签: regex pattern-matching elixir


    【解决方案1】:

    您可以简单地检查字符串的大小。因为它是十六进制,所以你可以使用byte_size/1(还有String.length/1 用于unicode 字符串):

    def handle_info({:elixir_serial, serial, data}, state) do
      [head | _tail] = String.split(data, "\r\n")
      new_state = state <> data
      case new_state do
        rfid when byte_size(rfid) == 12 ->
          #do something with RFID
          {:noreply, ""}
        _ ->
          {:noreply, new_state}
      end
    end
    

    请务必在您的 init 函数中将初始状态设置为空字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      相关资源
      最近更新 更多