const_reference prefix() const;
概要
マッチした文字列の前の文字列を指すサブマッチを返す。
要件
ready() == true
戻り値
マッチした文字列の前の文字列を指すサブマッチ。ただし、マッチが失敗した場合は未規定。
具体的なサブマッチの各メンバ変数の設定内容は以下の通り。
regex_matchの引数にmatch_resultsオブジェクトmを渡した場合、戻り値がtrueであれば、m.prefix().firstとm.prefix().secondは共に検索対象文字列の先頭となる。
また、m.prefix().matchedはfalseとなる。
戻り値がfalseの場合は未規定である。regex_searchの引数にmatch_resultsオブジェクトmを渡した場合、戻り値がtrueであれば、m.prefix().firstは検索対象文字列の先頭となり、m.prefix().secondはm[0].first(つまり、マッチした文字列の先頭)と等しくなる。
また、m.prefix().matchedはm.prefix().first != m.prefix().secondの結果となる(つまり、m.prefix()が空文字であればfalse、そうでなければtrue)。
戻り値がfalseの場合は未規定である。regex_iteratorを間接参照したオブジェクトの場合、当該オブジェクトをmとすると、m.prefix().firstは最初のマッチでなければ直前のマッチの際のm[0].second(つまり直前にマッチした文字列の末尾)、最初のマッチであれば検索対象文字列の先頭となり、m.prefix().secondはm[0].first(つまり、マッチした文字列の先頭)と等しくなる。
また、m.prefix().matchedはm.prefix().first != m.prefix().secondとなる(つまり、m.prefix()が空文字であればfalse、そうでなければtrue)。
例
#include <iostream>
#include <iterator>
#include <regex>
#include <string>
void print(const char* title, const std::ssub_match& sub, const std::string& s)
{
std::cout << title << ": str() = '" << sub.str() << "', "
"range = [" << sub.first - std::begin(s) << ", " << sub.second - std::begin(s) << "), "
"matched = " << std::boolalpha << sub.matched << std::endl;
}
int main()
{
// regex_match の場合
std::cout << "regex_match" << std::endl;
{
const std::string s = "0123";
const std::regex re("\\d+");
std::smatch m;
if (std::regex_match(s, m, re)) {
print("m[0]", m[0], s);
print("prefix()", m.prefix(), s);
} else {
std::cout << "not match" << std::endl;
}
}
std::cout << std::endl;
// regex_search の場合
std::cout << "regex_search" << std::endl;
{
const std::string s = " abc 0123 defgh ";
const std::regex re("\\d+");
std::smatch m;
if (std::regex_search(s, m, re)) {
print("m[0]", m[0], s);
print("prefix()", m.prefix(), s);
} else {
std::cout << "not match" << std::endl;
}
}
std::cout << std::endl;
// regex_iterator の場合
std::cout << "regex_iterator" << std::endl;
{
const std::string s = "abc 0123";
const std::regex re("\\w+");
for (std::sregex_iterator it(std::begin(s), std::end(s), re), end; it != end; ++it) {
auto&& m = *it;
print("m[0]", m[0], s);
print("prefix()", m.prefix(), s);
std::cout << std::endl;
}
}
}
出力
regex_match
m[0]: str() = '0123', range = [0, 4), matched = true
prefix(): str() = '', range = [0, 0), matched = false
regex_search
m[0]: str() = '0123', range = [5, 9), matched = true
prefix(): str() = ' abc ', range = [0, 5), matched = true
regex_iterator
m[0]: str() = 'abc', range = [0, 3), matched = true
prefix(): str() = '', range = [0, 0), matched = false
m[0]: str() = '0123', range = [4, 8), matched = true
prefix(): str() = ' ', range = [3, 4), matched = true
バージョン
言語
- C++11
処理系
- Clang: 3.0 ✅, 3.1 ✅, 3.2 ✅, 3.3 ✅, 3.4 ✅, 3.5 ✅, 3.6 ✅
- GCC: 4.9.0 ✅, 4.9.1 ✅, 5.0.0 ✅
- ICC: ??
- Visual C++: ??