LoginSignup
9
7

More than 5 years have passed since last update.

c++でサクッと正規表現を使う

Last updated at Posted at 2018-10-03

正規表現にマッチしているかどうかを判定したい文字列に対して、
std::smatch のインスタンスを作成、std::regex で正規表現を指定、std::regex_search で判定する。
std::regex で指定する正規表現が正しいかどうかは、
事前に正規表現エディタ(https://regexr.com/ 等) で確認しておくと楽。


#include <iostream>
#include <regex>

int main()
{
    // char* 版
    // regex_search の 最初の引数が 「const char*」
    std::cmatch cmatch;
    if (std::regex_search("sabc", cmatch, std::regex("^(abc|ABC)")))
    {
        // ここには来ないはず
    }

    // string 版
    std::string str = "abce";
    std::smatch smatch;
    if (std::regex_search(str, smatch, std::regex("^(abc|ABC)")))
    {
        // ここに来るはず
    }

    // wstring 版
    std::wstring wstr = L"abc";
    std::wsmatch wmatch;
    if (std::regex_search(wstr, wmatch, std::wregex(L"^(abc|ABC)")))
    {
        // ここに来るはず
    }

    return 0;
}
9
7
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
9
7