Visual C++ 2010 で正規表現

Visual C++ 2010でTR1で定義されていた正規表現がstd名前空間に取り込まれて使用できるようになったということで、試してみる。
TR1ということで、使い方はboostとほぼ同じようです。


regex_searchで、正規表現にマッチさせる

#include <regex>
#include <string>
#include <iostream> 
 
int main() 
{
    std::regex re("[0-9]+");
    std::match_results<const char *> results;
  
    if (!std::regex_search("xxx123456yyy", results, re, std::regex_constants::match_default)) {
        return 1;
    }

    std::cout << "prefix: " << results.prefix().str() << std::endl;
    std::cout << "suffix: " << results.suffix().str() << std::endl;
    std::cout << "posision: " << results.position() << std::endl;
    std::cout << "str: " << results.str() << std::endl;

    std::match_results<const char *>::const_iterator it = results.begin();
    while (it != results.end()) {
        if (it->matched) {
            std::cout << "sub_match: " << it->str() << std::endl;
        }
        it++;
    }
  
    return 0;
}

  • 実行結果
  • prefix: xxx
    suffix: yyy
    posision: 3
    str: 123456
    sub_match: 123456






    regex_replaceで正規表現マッチした文字列を置換する

    #include <regex>
    #include <string>
    #include <iostream> 
     
    int main() 
    {
        std::regex re("Ruby");
        std::string s = "I love Ruby!, You love Ruby!";
        std::string replaced;
        
        replaced = std::regex_replace(s, re, std::string("Java"), std::regex_constants::match_default);
        std::cout << replaced << std::endl;
      
        return 0;
    }

  • 実行結果
  • I love Java!, You love Java!






    regex_replaceで、大文字・小文字を区別せずにマッチした文字列を、置換する

    #include <regex>
    #include <string>
    #include <iostream> 
     
    int main() 
    {
        //std::regex_constants::icaseで大文字・小文字を区別せずにマッチさせる
        std::regex re("Ruby|Perl|Python", std::regex_constants::icase);
        std::string s = "I love ruby!, You love perl!, We love python.";
        std::string replaced;
        
        replaced = std::regex_replace(s, re, std::string("Java"), std::regex_constants::match_default);
        std::cout << replaced << std::endl;
      
        return 0;
    }

  • 実行結果
  • I love Java!, You love Java!, We love Java.