正規表現を raw string literals で定義

Boost.Regex 等で特殊表現を定義する場合に \ を使用するんですが、エスケープシーケンスを回避する為に \\ と既述する必要があります。

boost::regex r("^\\s*\\d+\\-\\d+\\s*$");
assert( boost::regex_match("12-34", r));
assert( boost::regex_match("  12-34   ", r));
assert(!boost::regex_match("12-ab", r));
assert(!boost::regex_match("1234", r));
assert(!boost::regex_match("  a12-34", r));


こういう時に raw string literals を使用すると \ をそのまま使用することが出来ます。

[ソース]

#include <boost/regex.hpp>

int
main(){
    boost::regex r(R"(^\s*\d+\-\d+\s*$)");

    assert( boost::regex_match("12-34", r));
    assert( boost::regex_match("  12-34   ", r));
    assert(!boost::regex_match("12-ab", r));
    assert(!boost::regex_match("1234", r));
    assert(!boost::regex_match("  a12-34", r));

    return 0;
}


raw string literals 便利ですね。