以下输出“>Hut”,我希望它输出“Hut”。我知道 .* 是贪婪的,但 > 必须匹配并且它在捕获组之外,所以为什么它在我的子匹配中?
#include <string>
#include <regex>
#include <iostream>
using namespace std;
int main() {
regex my_r(".*>(.*)");
string temp(R"~(cols="64">Hut)~");
smatch m;
if (regex_match(temp, m, my_r)) {
cout << m[1] << endl;
}
}
最佳答案
这是 libstdc++ 实现中的一个错误。观看这些:
#include <string>
#include <regex>
#include <boost/regex.hpp>
#include <iostream>
int main() {
{
using namespace std;
regex my_r("(.*)(6)(.*)");
smatch m;
if (regex_match(std::string{"123456789"}, m, my_r)) {
std::cout << m.length(1) << ", "
<< m.length(2) << ", "
<< m.length(3) << std::endl;
}
}
{
using namespace boost;
regex my_r("(.*)(6)(.*)");
smatch m;
if (regex_match(std::string{"123456789"}, m, my_r)) {
std::cout << m.length(1) << ", "
<< m.length(2) << ", "
<< m.length(3) << std::endl;
}
}
return 0;
}
如果你用 gcc 编译,第一个 (libstdc++) 返回完全错误的结果 9, -2, 4 而第二个(boost 的实现)返回 5, 1, 3 正如预期的那样。
如果您使用 clang + libc++ 进行编译,您的代码可以正常工作。
(请注意,libstdc++ 的正则表达式实现仅“部分支持”,如 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52719 中所述。)
关于C++ 正则表达式不理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10892890/