在C++中,unmatchedgroup的位置是什么?
让m是类型std::smatch。假设有一个不匹配的组i。什么是
m.position(i)?就此而言,什么是m[i]?
例如,考虑
std::regex re {"^(a+)|(b+)"};
string target="aa";
std::smatch m;
std::regex_search(target,m,re);
cout<<"m[2] is: "<<m[2]<<" at position: "<<m.position(2);
我无法从参考https://en.cppreference.com/w/cpp/regex/match_results/position 中弄清楚这里保证会发生什么以及为什么。
回答
根据 C++17 标准:
28.10
Class template match_results[re.results]4存储在索引 0 处的 sub_match 对象代表子表达式 0,即整个匹配。在这种情况下,匹配的 sub_match 成员始终为真。存储在索引 n 处的 sub_match 对象表示匹配表达式中与标记的子表达式 n 匹配的内容。如果子表达式 n 参与了正则表达式匹配,则匹配的 sub_match 成员计算结果为真,成员 first 和 second 表示形成该匹配的字符范围 [first,second)。否则匹配为假,成员 first 和 second 指向被搜索序列的末尾。
[注意:表示不参与正则表达式匹配的不同子表达式的 sub_match 对象不需要是不同的。— 尾注]
现在m.position(n)返回(*this)[n].first。
鉴于“[If] 匹配为假,[then] 成员第一个和第二个指向被搜索序列的末尾” ......
这意味着m.position(n)应该指向“被搜索序列的末尾”。
- The reason cppreference is easier to read is precisely because it doesn't go into as much detail as the standard needs to.