简体   繁体   English

c ++正则表达式模式来检查文件扩展名

[英]c++ regex pattern to check file extension

I want to check if a string ends with .h5 and tried the c++ regex class.我想检查一个字符串是否以 .h5 结尾并尝试了 c++ regex 类。 But for any Input the regex_search function returns false.但是对于任何输入,regex_search 函数都返回 false。 Other examples in the internet looks similar to my code below, so I do not understand whats going wrong.互联网上的其他示例看起来与我下面的代码相似,所以我不明白出了什么问题。

What is wrong with my code?我的代码有什么问题? Thanks for any help.谢谢你的帮助。

#include <iostream>
#include <regex>
#include <string>

int main(int argc,char *argv[]){

  std::string text = argv[1];

  std::regex rx(".*\\.h5$");
  bool found = std::regex_search(text.c_str(),rx);

  std::cout << text << std::endl;
  std::cout << "res: " << found << std::endl;


}

What about using just substr ?只使用substr怎么样?

#include <string>

int main (int argc, char* argv[]) {
  std::string filename(argv[1]);
  std::string last = filename.substr(filename.length() - 3);

  return last == ".h5";
}

Replace regex_search with regex_matchregex_match替换regex_search

std::regex rx(".*\\.h5$");
bool found = std::regex_match(argv[1], rx);
std::cout << "Result: " << std::boolalpha << found << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM