我有以下代码:
include <regex>
include <string>
TCHAR basePath[MAX_PATH];
GetCurrentDirectory(MAX_PATH, basePath);
wstring test(&basePath[0]); //convert to wstring
string test2(test.begin(), test.end()); //and convert to string.
std::regex rBase("(.*my-dir)");
std::smatch sm;
std::regex_match(test2, sm, rBase);
但是,sm总是返回空
基本上如果我有以下目录结构:
E:\foo\bar\baz\my-dir\post1\dir2
我要回去
"E:\foo\bar\baz\my-dir"
如果我运行正则表达式,比如 python 或 javascript,它似乎可以工作,但在 C++ 中则不行
我缺少什么或有哪些替代方案?
谢谢
最佳答案
std::regex_match
检查整个字符串是否匹配正则表达式,而不仅仅是它的任何部分。
使用 std::regex_search
而不是 std::regex_match
或使用匹配整个字符串的正则表达式,例如 "(.*my-dir ).*"
,并用sm[1].str()
提取子匹配。
关于C++ 正则表达式不适用于 PCRE 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28418314/