2009年1月28日水曜日

boost regex でURIパーズ

boost のregular expression library を使って URIをパーズ.こちらのページを参考に.ただちょっと古いようでreg_expression -> basic_regexと読み替えてやる必要がある.

しかし,テンプレートを使ったC++のライブラリの出すエラーメッセージは解読不能だ.1カ所ちょっと使うクラスを間違えただけで,みっしり数百行もエラーが出るのはどうなんだろう? 気の弱いプログラマなら卒倒しかねないぞ.しかもエラーメッセージを見てもまったくエラーの原因がわからないし.やっぱりtemplateは好きになれないなあ.まあ理解不能なメッセージという意味では,latexも似たようなものだが.

#include 
#include 
/**
 *  assumed URI
 *  scheme://[user@][host][:port]/[path][?query][#fragment]
 */
class URI {
public:
  std::string scheme;
  std::string authority;
  std::string user;
  std::string host;
  int         port;
  std::string path;
  std::string query;
  std::string fragment;

  URI(std::string s) {
    static const char * pattern = "\\A([^:]+)://"   // scheme
      "((?:([^:/@]*)@)?([^:@/]*)(?::(\\d+))?)/"   // authority = [user-info@]host[:port]
      "([^\\?]*)(?:\\?([^#]*))?(?:#(.*))?\\z";    // body = [path?query#fragment]

    static const boost::regex e(pattern);
    boost::smatch match;
    regex_match(s, match, e);
    this->scheme    = match[1].str();
    this->authority = match[2].str();
    this->user      = match[3].str();
    this->host      = match[4].str();
    this->port      = atoi(match[5].str().c_str());
    this->path      = match[6].str();
    this->query     = match[7].str();
    this->fragment  = match[8].str();
  }
};

0 件のコメント: