问题:
我知道我可以通过以下方式获取文件名:
std::string wholePath = "/User/home/Lib/hello.cpp.h";
std::regex e(".*\\/(.*)\\..*$");
std::smatch sm;
std::regex_match(wholePath.cbegin(), wholePath.cend(), sm, e);
std::cout << "File Name is : " << sm[1];
Run Code Online (Sandbox Code Playgroud)
但我不知道如何从中获取文件名:
std::string wholePath = "\User\home\Lib\hello.cpp.h";
std::regex e_1(".*\(.*)\\..*$");
std::regex e_2(".*\\(.*)\\..*$");
std::regex e_3(".*\\\(.*)\\..*$");
std::regex e_4(".*\\\\(.*)\\..*$");
std::smatch sm;
// std::regex_match(wholePath.cbegin(), wholePath.cend(), sm, e);
Run Code Online (Sandbox Code Playgroud)
我已经尝试了上述四个表达式,但它们都不起作用。
我的问题,如何匹配字符'\'。
帮助 /。\
使用std::string::find_last_of()可能更好
std::string Path;
std::string FileName;
// find last '/' or '\\' symbol in source string
std::string::size_type found = str.find_last_of("/\\");
// if we found one of this symbols
if(found!=std::string::npos){
// path will be all symbols before found position
Path = str.substr(0,found);
// filename will be all symbols after found position
FileName = str.substr(found+1);
} else { // if we not found '/' or '\\'
// path will be empty
Path.clear();
// and source string will contain file name
FileName = str;
}
std::cout << "Path: " << Path << '\n';
std::cout << "FileName: " << FileName << std::endl;
Run Code Online (Sandbox Code Playgroud)