0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C++ 正規表現 サンプル

Posted at

introduction

C++ で正規表現を使うことがあったので、サンプルとして提供します。

下のWebアプリを作った際、MySQLのコマンドを書くときに使用したものです。

MySQL について

軽くMySQLについて説明しておきます。
以下のURLに記されているように文字の中でも特殊文字エスケープシーケンスと呼ばれるものがあります。
'」や「"」 などの文字ですね。これらをMySQLコマンドに載せたい場合は「'」「"」のように書く必要があります。

C++ で正規表現を使う

regexというライブラリを使います。またC++11の生文字リテラルを使用します。

# include <iostream>
# include <regex>
# include <string>

string sqlText(string text) {
    std::regex re(R"("|'|\\)");
    const std::string fmt = R"(\$&)";
    string formated_text = std::regex_replace(text, re, fmt);
    // cout << "ss == " << formated_text << endl;
    return formated_text;
}

sqlTextの一行目で正規表現で探したいものを設定します。今回は「'」「"」「\」を探すことにしました。

fmtで何を入れ替えるか明示します。今回はreで探した文字を先頭にバックスラッシュをつけた状態にします。

std::regex_replaceを用いて実際の処理をします。

以上

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?