C/C++实现字符串模糊匹配

2020-01-06 15:02:25王旭
C++,字符串,模糊匹配

  需求满足了,我担心的还有一个问题,那就是性能,注释掉cout输出,将while z语句调至1,000,000,重新编译跑一下:

  time ./fnmatch

C++,字符串,模糊匹配

看来效率还不错,2.1s 进行了100W次匹配,平均2us一次,性能要求也满足了...

附:上面文章只介绍了在Linux系统下直接调用系统函数fnmatch即可实现,而没有考虑在Windows在的使用。

本人这周看了下Google-glog代码,恰巧发现了一个类似fnmatch的简单实现,因此综合起来提供了一个跨平台的接口。


#ifdef OS_WINDOWS
/* Bits set in the FLAGS argument to `fnmatch'. copy from fnmatch.h(linux) */
#define  FNM_PATHNAME  (1 << 0) /* No wildcard can ever match `/'. */
#define  FNM_NOESCAPE  (1 << 1) /* Backslashes don't quote special chars. */
#define  FNM_PERIOD    (1 << 2) /* Leading `.' is matched only explicitly. */
#define  FNM_NOMATCH    1

#define fnmatch fnmatch_win

/**copy from Google-glog*/
bool SafeFNMatch(const char* pattern,size_t patt_len,const char* str,size_t str_len)
{
  size_t p = 0;
  size_t s = 0;
  while (1)
  {
    if (p == patt_len && s == str_len)
      return true;
    if (p == patt_len)
      return false;
    if (s == str_len)
      return p+1 == patt_len && pattern[p] == '*';
    if (pattern[p] == str[s] || pattern[p] == '?')
    {
      p += 1;
      s += 1;
      continue;
    }
    if (pattern[p] == '*')
    {
      if (p+1 == patt_len) return true;
      do
      {
        if (SafeFNMatch(pattern+(p+1), patt_len-(p+1), str+s, str_len-s))
        {
          return true;
        }
        s += 1;
      } while (s != str_len);

      return false;
    }

    return false;
  }
}

/**注意:Windows平台下尚未实现最后一个参数flags的功能!!!*/
int fnmatch_win(const char *pattern, const char *name, int flags = 0)
{
  if(SafeFNMatch(pattern,strlen(pattern),name,strlen(name)))
    return 0;
  else
    return FNM_NOMATCH;
}

#else
#include <fnmatch.h>
#endif

int main()
{
  const char* orgin_str = "sina|weibo|pusher";
  char pattern_arr[][20] = {
    {"sina|*|pusher"},
    {"sina|*|*"},
    {"*|weibo|*"},
    //不能被匹配的
    {"sina|pic|*"},
    {"*|*|sign"},
    {"*|weibo|sign"},
    {"*|pic|sign"},
    {"sina|pic|sign"},

    {"*|*|*"}
  };
  static int pattern_arr_size = sizeof(pattern_arr) / sizeof(pattern_arr[0]);

  vector<char *> vec_str;
  for(int i = 0; i < pattern_arr_size; i ++)
  {
    vec_str.push_back(pattern_arr[i]);
  }

  std::cout << "Origin Str: " << orgin_str << "nn";
  int ret;
  for(int i = 0; i < vec_str.size(); i++)
  {
    ret = fnmatch(vec_str.at(i), orgin_str, FNM_PATHNAME);
    if(ret == FNM_NOMATCH)
    {
      cout<<"sorry, I'm failed: ["<< vec_str.at(i) <<"]n";
    }
    else
    {
      cout<<"OK, I'm success: ["<< vec_str.at(i) <<"]n";
    }
  }

  return 0;
}