httpリクエストヘッダの正規表現処理
今まで正規表現処理を行う場合はCAtlRegExpとCAtlREMatchContextを使っていたがVS2008SP1環境では使えなくなっているっぽい。あまりboostを使いたくないけど他に簡単に実現できる方法がないのでしぶしぶBoostを使用して見たのが下記サンプル。httpリクエストヘッダからデータをパースしている
BOOL bExistMethod = FALSE; BOOL bExistHostField = FALSE; BOOL bExistUserAgent = FALSE; CStringA strMethod = ""; CStringA strURI = ""; CStringA strAddress= ""; CStringA strPort= ""; CStringA strUserAgent = ""; for (int i = 0; i < fileSize; ++i) { if (pBuf[i] == '\r') { bCR = TRUE; continue; } if (pBuf[i] == '\n' && bCR == TRUE) { if (bExistMethod == FALSE) { #ifdef _DEBUG CStringA strLine((char *)(pBuf + lineStartPos), i - lineStartPos + 1); OutputDebugStringA(strLine); #endif std::tr1::regex expression("^([A-Z]{3,4}) +(/.*) +HTTP/[0-9]+.[0-9]+"); //std::tr1::regex expression("^GET +(/.*) +HTTP/[0-9]+.[0-9]+"); std::string tag((char *)pBuf + lineStartPos, i - lineStartPos + 1); // 行の先頭のポインタ、行の長さ指定 std::tr1::smatch match; if (std::tr1::regex_search(tag, match, expression)) { strMethod = match.str(1).c_str(); strURI = match.str(2).c_str(); bExistMethod = TRUE; } } if (bExistHostField == FALSE) { #ifdef _DEBUG CStringA strLine((char *)(pBuf + lineStartPos), i - lineStartPos + 1); OutputDebugStringA(strLine); #endif std::tr1::regex expression("^Host *: +([A-Za-z0-9.]+)( +: +([0-9]{1,5}))?"); std::string tag((char *)pBuf + lineStartPos, i - lineStartPos + 1); std::tr1::smatch match; if (std::tr1::regex_search(tag, match, expression)) { strAddress = match.str(1).c_str(); strPort = match.str(3).c_str(); bExistHostField = TRUE; } } if (bExistUserAgent == FALSE) { #ifdef _DEBUG CStringA strLine((char *)(pBuf + lineStartPos), i - lineStartPos + 1); OutputDebugStringA(strLine); #endif std::tr1::regex expression("^User-Agent *: +(.+)"); std::string tag((char *)pBuf + lineStartPos, i - lineStartPos + 1); std::tr1::smatch match; if (std::tr1::regex_search(tag, match, expression)) { strUserAgent= match.str(1).c_str(); bExistUserAgent = TRUE; } } lineStartPos = i + 1; // 行の先頭を次に進める } bCR = FALSE; // 初期化 }
因みにpBufには下記のデータが格納されている
GET / HTTP/1.1 Host: www.google.co.jp User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; ja; rv:1.9.0.13) Gecko/2009073022 Firefox/3.0.13 (.NET CLR 3.5.30729) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: ja,en-us;q=0.7,en;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: Shift_JIS,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive