Newer
Older
m5stickcplus / src / regexp01.ino
@Motoki Motoki on 15 Mar 1 KB 2025
#include <Regexp.h>
#include <Dictionary.h>

Dictionary *dict = new Dictionary(); // 辞書/ハッシュ。キー文字列→値 を保持するデータ構造

void match_callback  (const char * match,         // matching string (not null-terminated)
                      const unsigned int length,  // length of matching string
                      const MatchState & ms)      // MatchState in use (to get captures)
{
  char k [10];   // size must be large enough to hold captures
  char v [10];   // size must be large enough to hold captures
  ms.GetCapture(k, 0);
  ms.GetCapture(v, 1);
  dict->insert(k, v); // 辞書に追加 (たとえば、 red→120 を追加)
}  // end of match_callback

// たとえば、*cbuf = "red=120&green=255&blue=9" のような文字列を想定する
void param2dict(char *cbuf){
      MatchState ms (cbuf); //正規表現マッチャーの作成
      ms.GlobalMatch ("([a-z]+)=([0-9]+)", match_callback); // (key)=(value) で複数回マッチングする。match_callback は別関数。
      int r = dict->search("red").toInt(); // 辞書 dict
      int g = dict->search("green").toInt();
      int b = dict->search("blue").toInt();
      int32_t bgcolor = (int(r * 31 / 255) << 11) | (int(g * 63 / 255) << 5) | (int(b * 31 / 255));
}