Previous Page | Next Page

C++/STLで正規表現

今まで正規表現を使いたい場合、とっとと別の言語に切り替えていた私ですが、Boostというライブラリの正規表現パッケージを使ってみました。Boostのサイトにはサンプルはあるのですが、C++/STLでさくっと正規表現を使うにはイマイチ感があったので、覚書ということでサンプルのせます。ちなみに、Boostのインストール等の情報はLet's Boostがお勧めです。
若干ですがコードの説明を、サンプルはHTTPのレスポンスヘッダ(WEBサーバーからの戻りヘッダ)からCookie情報を取得するものです。関数 boost::regex_search が正規表現を使って文字列の検索を行っています。
その他、正規表現の利用法として入力値のチェックもあるかと思います。その場合、boost::regex_matchという関数が使えます。

#include <boost/regex.hpp>
#include <iostream>
int main(int , char* [])
{
  // 検索対象文字列
  std::string str( "HTTP/1.1 200 OK\r\n"
  "Server: Apache\r\n"
  "Set-Cookie: NAME1=VAL1\r\n"
  "Set-Cookie: NAME2=VAL2; expires=Mon, 18-02-2008 23:30:45 GMT\r\n"
  "Set-Cookie: NAME3=VAL3; path=path\r\n"
  "Set-Cookie: NAME4=VAL4; path=path; domain=example\r\n"
  "Set-Cookie: NAME5=VAL5; path=path; domain=example; secure\r\n"
  "Connection: close\r\n"
  "Content-Type: text/html\r\n");
  // 正規表現
  boost::regex r(
    "^Set-Cookie:\\s*([^;$\\s]+);?(?:\\s*expires=([^;$]+);?)?"
    "(?:\\s*path=([^;$\\s]+);?)?(?:\\s*domain=([^;$\\s]+);?)?"
    "\\s*(secure)?\\s*$"
    );
  boost::smatch what;  // マッチ文字列参照オブジェクト
  std::string::const_iterator start = str.begin();
  std::string::const_iterator end = str.end();
  // 検索対象の文字列から正規表現にマッチする文字列(複数有)を取り出す
  while ( boost::regex_search(start, end, what, r) ) {
    // 取得した文字列をstringに代入する(smatchにはイテレーターが入る)
    std::string cookie(what[1].first, what[1].second);
    std::string expires(what[2].first, what[2].second);
    std::string path(what[3].first, what[3].second);
    std::string domain(what[4].first, what[4].second);
    std::string secure(what[5].first, what[5].second);
    std::cout << cookie << ":" << expires << ":" << path << ":"
              << domain << ":" << secure  << ":" << std::endl;
    start = what[0].second;  // 次のマッチ文字列を取得する
  }
   return 0;
}
2008-02-20 | コメント:3件
Phillip Espinoより
2026-02-08 05:57:58
Our AI-driven service brings location-targeted visitors to your site, significantly cheaper than traditional paid advertising. Ready to boost your conversions?

https://ow.ly/mtUs50XSIJZ
Neil Denhamより
2026-02-08 07:06:46
Drive keyword-specific traffic from targeted locations to your website with our AI-driven service, all at a budget-friendly rate. Connect with us to get started.

https://marketingaged.com/
Brayden Massieより
2026-02-08 07:06:49
Is your ohfuji.name website missing out on leads? See how our AI can fix that: https://www.youtube.com/shorts/iojvp6ZtjW4

コメントをどうぞ


コメントをされる前に『不適切なコメントへの対応』を一読下さい。

Previous Page | Next Page