使用g+时的不同结果+;和visual studio 14 2015编译器,使用c+中的正则表达式+; 我在C++中玩正则表达式,注意到G++(MINW)和Visual Studio 14 2015编译器(Windows上的)之间的一些不规则性。以下是我试用过的代码: #include <iostream> #include <vector> #include <string> #include <regex> static const std::string data = "\n a = 10\n b = 20\n"; int main(int argc, char* argv[]) { auto strIt = data.begin(); while (strIt != data.end()) { std::regex e("^[ \t\n\r]"); std::smatch m; std::string s(strIt, data.end()); if (std::regex_search(s, m, e)) { strIt += m[0].str().size(); } else { std::cout << "s = \"" << s << "\"" << '\n'; break; } } }

使用g+时的不同结果+;和visual studio 14 2015编译器,使用c+中的正则表达式+; 我在C++中玩正则表达式,注意到G++(MINW)和Visual Studio 14 2015编译器(Windows上的)之间的一些不规则性。以下是我试用过的代码: #include <iostream> #include <vector> #include <string> #include <regex> static const std::string data = "\n a = 10\n b = 20\n"; int main(int argc, char* argv[]) { auto strIt = data.begin(); while (strIt != data.end()) { std::regex e("^[ \t\n\r]"); std::smatch m; std::string s(strIt, data.end()); if (std::regex_search(s, m, e)) { strIt += m[0].str().size(); } else { std::cout << "s = \"" << s << "\"" << '\n'; break; } } },c++,visual-studio-2015,g++,C++,Visual Studio 2015,G++,但是当使用VisualStudio编译器时,它会 s = "b = 20\n" 忽略整个“a=10”部分。在VisualStudio中通过调试功能进一步研究之后,我看到m变量保存了“a=10”部分后面的空格 你知道它为什么会这样吗?我是不是在某个地方犯了一个大错误却没有注意到?请帮助。首先,一个简化的示例: #include <iostream> #include <string> #include <regex> using namespace std;

但是当使用VisualStudio编译器时,它会

s = "b = 20\n"
忽略整个“a=10”部分。在VisualStudio中通过调试功能进一步研究之后,我看到m变量保存了“a=10”部分后面的空格


你知道它为什么会这样吗?我是不是在某个地方犯了一个大错误却没有注意到?请帮助。

首先,一个简化的示例:

#include <iostream>
#include <string>
#include <regex>

using namespace std;

int main() {
    const string data = "abc\nXabc";
    regex re("^X");
    smatch match;
    if (regex_search(data, match, re))
        cout << "match: " << match.str() << endl;
    else
        cout << "no match" << endl;
    return 0;
}


MinGW的行为在C++ 17标准下是正确的。

可能与你的问题无关——但是你不必创建<代码> s >代码>,你可以做<代码> ReXEXY搜索(Struts,Dead,Enter),m,e);代码>是的,现在它应该可以输出所有内容了。对此我很抱歉。所以在VisualStudio上无法获得相同的行为?我想我将不得不用空格替换每条换行符。@Ugi您可以使用
regex\u match
而不是
regex\u search
#include <iostream>
#include <string>
#include <regex>

using namespace std;

int main() {
    const string data = "abc\nXabc";
    regex re("^X");
    smatch match;
    if (regex_search(data, match, re))
        cout << "match: " << match.str() << endl;
    else
        cout << "no match" << endl;
    return 0;
}
regex re("^X", regex_constants::multiline);