file name matching with wildcard

前端 未结 7 1618
闹比i
闹比i 2021-01-01 16:14

I need to implement something like my own file system. One operation would be the FindFirstFile. I need to check, if the caller passed something like ., sample*.cpp

7条回答
  •  有刺的猬
    2021-01-01 16:52

    Here is a dependency free portable C++ version:

    #include 
    
    #include 
    
    bool wild_match(const std::string& str, const std::string& pat) {
      std::string::const_iterator str_it = str.begin();
      for (std::string::const_iterator pat_it = pat.begin(); pat_it != pat.end();
           ++pat_it) {
        switch (*pat_it) {
          case '?':
            if (str_it == str.end()) {
              return false;
            }
    
            ++str_it;
            break;
          case '*': {
            if (pat_it + 1 == pat.end()) {
              return true;
            }
    
            const size_t max = strlen(&*str_it);
            for (size_t i = 0; i < max; ++i) {
              if (wild_match(&*(pat_it + 1), &*(str_it + i))) {
                return true;
              }
            }
    
            return false;
          }
          default:
            if (*str_it != *pat_it) {
              return false;
            }
    
            ++str_it;
        }
      }
    
      return str_it == str.end();
    }
    

提交回复
热议问题