我在 VS2013 Update 4 和 VS2015 Update 3 中使用以下 C++ 代码,使用字符范围尝试不区分大小写地匹配并替换出现的位置:
std::wstring strSource(L"Hallo Welt, HALLO WELT");
std::wstring strReplace(L"ello");
std::regex_constants::syntax_option_type nReFlags =
std::regex::ECMAScript |
std::regex::optimize |
std::regex::icase;
std::wregex re(L"[A]LLO", nReFlags);
std::wstring strResult = std::regex_replace(strSource, re, strReplace);
wcout << L"Source: \"" << strSource.c_str() << L"\"" << endl
<< L"Result: \"" << strResult.c_str() << L"\"" << endl;
我期望输出:
Source: "Hallo Welt, HALLO WELT"
Result: "Hello Welt, Hello WELT"
但是我得到:
Source: "Hallo Welt, HALLO WELT"
Result: "Hello Welt, HALLO WELT"
为什么字符范围不区分大小写? 为什么第二个匹配项似乎没有找到并被替换?
最佳答案
我觉得这可能是 Visual Studio 中的一个错误。如果您从 [A]
中删除括号,它会正常工作。
std::wregex re(L"ALLO", nReFlags);
奇怪的是,如果您使用 regex_search
,它会找到 2 个匹配...
std::wregex re(L"([A]LLO)", nReFlags);
std::wsmatch match;
std::regex_search(strSource, match, re);
for (auto i = 0; i < match.size(); ++i)
std::wcout << match[i] << "\n";
关于c++ -::std::regex_replace with syntax flag icase on Windows (VS2013 Update 4, VS2015 Update 3) 不匹配使用字符范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37026965/