【问题标题】:How to extract file extension from url如何从url中提取文件扩展名
【发布时间】:2014-05-21 12:21:27
【问题描述】:

我有 url http://faq.sipbroker.com/tiki-index.php?page=phone+numbers,我需要从 url 中提取文件扩展名(在这种情况下为php)。 我只能使用 C++ 和 Boost。 我怎么能做到这一点?有一些例子,但还有一些其他的 libls,比如 Poco 等......但我只能使用 Boost

【问题讨论】:

    标签: c++ visual-c++ boost


    【解决方案1】:

    在这种情况下,方案是http。提取方案非常容易,因为 uri 以方案开头,后跟冒号。 您正在寻找的是hierarchical part 的一部分。要扫描此部分以查找您解释为文件扩展名的子字符串是一项复杂的任务。如果您不想使用某个库,您可能需要查看一个库(例如cppnetlib uri)并复制现有 uri 解析器的一些代码。真的不简单。

    cpp-netlib uri 使用 boost::spirit 作为解析器。你可以在uri_parser.cpp找到实现

    编辑: 我认为您想提取要解释为文件扩展名的内容。如果您将“文件扩展名”定义为(可选)query part 之前最后一个点之后的字符,则可以采用简化的方法。

    查询组件由第一个问题表示 标记 ("?") 字符并以数字符号 ("#") 字符结尾 或在 URI 的末尾。

    std::string::size_type FindNth(const std::string& str, char c, unsigned n){
        std::string::size_type pos = 0;
        for (unsigned i = 0; i < n; ++i)
            pos = str.find(c, pos + 1);
        return pos;
    }
    
    std::string FindExension(const std::string& uri) {
        auto path = FindNth(uri, '/', 3);
        if (path == std::string::npos)
            return "";
        auto query = uri.find('?', path);
        auto dot = uri.rfind('.', query);
        if (dot == std::string::npos || dot < path)
            return "";
        return uri.substr(dot, query - dot);
    }
    

    【讨论】:

      【解决方案2】:

      编辑:这里所谓的scheme,根据hansmaad 的回答,实际上称为hierarchical part。反正我的回答原则应该很清楚了。

      我会反过来做:定义所有可能的方案,然后编写一个小函数,使用std::string::find 搜索其中一个方案:

      #include<string>
      #include<array>
      #include<iostream>
      
      std::string find_scheme(const std::string& url)
      {
          static std::array<std::string,2> scheme = {{"php", "whatever"}};
      
          for(int i=0;i<scheme.size();++i)
          {
              if(url.find(scheme[i])!=std::string::npos)
              {
                   return scheme[i];
              }
          }
      
          return "scheme not found";
      }
      
      
      int main()
      {
          std::string your_url = "http://faq.sipbroker.com/tiki-index.php?page=phone+numbers";
          std::cout<<find_scheme(your_url)<<std::endl;
      }
      

      这比从你的 url 字符串中提取一些子字符串更安全,甚至不需要提升。

      编辑:好的,“更安全”是相对的……我的意思是比手写程序更安全。然而,例如 http://www.php.com/tiki-index.asp,这样的 ansatz 就失败了。在这种情况下,要么调整 my

      【讨论】:

      • 在 www.baphphone.com/cgi-bin/foo.pl 上失败
      • 伙计,添加一个分号和一些包含在这里和那里......我的头不是编译器。
      • 致所有肯定都复制了 starks 结果的支持者:通过添加一个 include 与 gcc-4.7.2 无缝编译...现在继续进行 swarm 行为。跨度>
      猜你喜欢
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2012-10-11
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 2011-12-08
      相关资源
      最近更新 更多