1

Problem:
I know I can get the file name by this:

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];

But I don't know how to get the file name from this:

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);

I have tried the above four expressions and they are not working.
My question, How to match the char '\'.
Help /.\

Retired Ninja
  • 4,785
  • 3
  • 25
  • 35
sflee
  • 1,659
  • 5
  • 32
  • 63

2 Answers2

5

may be better to use 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;
  • The usage of `find_last_of` is good, but it's not yet complete. Observe what's happening if there is no slash: http://ideone.com/1LP5bP – stefan Mar 11 '15 at 08:01
  • @stefan this was not full example. Of course you need to check find_last_of result if(found!=std::string::npos) – DvoryankinEvgeny Mar 11 '15 at 08:05
  • Exactly right. You should add that to your answer, because right now, it isn't clear to every reader that you know it's incomplete. Your answer will be 2x better if the code is 100% correct and it will be 10x better if you explain what the code is doing and why. – stefan Mar 11 '15 at 08:07
  • 1
    Well the `else` part is missing, isn't it? ;-) – stefan Mar 11 '15 at 08:11
  • Thanks for the edit, it's really better now. One final suggestion: You may replace the output by assignment to a `path` and `file` variable and output the result just once (after all the logic). In my opinion, this would be a cleaner approach. Cheers! – stefan Mar 11 '15 at 08:31
2

In general '\' should be changed to '\\' when it's inside double quotation.

std::string wholePath = "\\User\\home\\Lib\\hello.cpp.h";
std::regex e(".*\\\\(.*)\\..*$");

But this method doesn't seem to work for splitting either Windows path or Unix path

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77