【问题标题】:Is there a better way to perform URL pattern matching in C++ than iteration?有没有比迭代更好的方法在 C++ 中执行 URL 模式匹配?
【发布时间】:2011-09-22 16:13:21
【问题描述】:

我有一个模式匹配例程,它根据用于请求命令的 URL 从 std::map 中查找值。 URL 映射表中的值如下:

// Assume this->commands_ is defined elsewhere as std::map<std::string, int>
// Providing a number of URL examples to give an idea of the structure of
// the URLs
this->commands_["/session"] = 1;
this->commands_["/session/:sessionid/url"] = 2;
this->commands_["/session/:sessionid/back"] = 3;
this->commands_["/session/:sessionid/forward"] = 4;
this->commands_["/session/:sessionid/element"] = 5;
this->commands_["/session/:sessionid/element/:id/text"] = 6;
this->commands_["/session/:sessionid/element/:id/value"] = 7;

每个 URL 模式中的标记(由前面的 ':' 指定)在对查找例程的调用中替换为实际值(例如,"/session/1234-8a0f/element/5bed-6789/text"),但我需要保留命名参数。上述示例中的命名标记列表并不详尽,在上面列出的位置中可能还有其他命名标记。请注意,令牌值是十六进制编码的数字。

目前,我正在遍历映射的键,用正则表达式值替换替换标记,并使用 std::tr1 正则表达式类对请求的值执行正则表达式匹配,将匹配的标记名称和值捕获到向量。该代码在功能上与此等价(为清楚起见,代码比通常编写的更冗长):

// Assume "using namespace std;" has been declared,
// and appropriate headers #included.
int Server::LookupCommand(const string& uri,
                          vector<string>* names,
                          vector<string>* values) {
    int value = 0;

    // Iterate through the keys of the map
    map<string, int>::const_iterator it = this->commands_.begin();
    for (; it != this->commands_.end(); ++it) {
        string url_candidate = it->first;

        // Substitute template parameter names with regex match strings
        size_t param_start_pos = url_candidate.find_first_of(":");
        while (param_start_pos != string::npos) {
            size_t param_len = string::npos;
            size_t param_end_pos = url_candidate.find_first_of("/",
                                                            param_start_pos);
            if (param_end_pos != string::npos) {
                param_len = param_end_pos - param_start_pos;
            }

            // Skip the leading colon
            string param_name = url_candidate.substr(param_start_pos + 1,
                                                     param_len - 1);
            names->push_back(param_name);
            url_candidate.replace(param_start_pos,
                                  param_len,
                                  "([0-9a-fA-F-]+)");
            param_start_pos = url_candidate.find_first_of(":");
        }

        tr1::regex matcher("^" + url_candidate + "$");
        tr1::match_results<string::const_iterator> matches;
        if (tr1::regex_search(uri, matches, matcher)) {
            size_t param_count = names->size();
            for (unsigned int i = 0; i < param_count; i++) {
                // Need i + 1 to get token match; matches[0] is full string.
                string param_value = matches[i + 1].str();
                values->push_back(param_value);
            }
            found_value = it->second;
            break;
        }
    }
    return value;
}

请注意,我没有使用 Boost 库,也不允许我在这个项目中使用它们。

我觉得这段代码效率非常低,因为我每次都在遍历地图的键,但是我无法看到众所周知的森林,而且我遇到了困难有替代品。虽然描述听起来很荒谬,但我实际上试图构建的是基于键的正则表达式匹配而不是精确匹配的映射查找。我怎样才能使它更有效率?我在设计这个函数时忽略了哪些模式?

【问题讨论】:

  • 有趣的问题。但是,从一开始就注意到std::map 在这里根本不是正确的数据结构。它基于键的相对顺序关系提供从精确键到值的映射。你想要一些完全不同的东西,即基于模式匹配关系的键到值的映射。
  • 同意地图不是正确的数据结构。我在这里使用它作为 vector 的功能等价物,我将在其中迭代矢量。当这个函数开始它的生命时,地图是正确的结构,但是在需求改变之后,我没有回去更正代码以使用不同的数据结构。最终,这就是问题所在:正确的数据结构是什么?

标签: c++ regex pattern-matching tr1


【解决方案1】:

在我看来,您可以将 URL 拆分为其组件(可能使用 here 中的建议之一),然后使用 decision tree 找到正确的模式。

在这棵树中,每个节点都是与 URL 的特定组件匹配的正则表达式,而叶子将是您当前存储在地图中的值:

                                 session
                                    |   \
                                    |    1
                                    |
                              ([0-9a-fA-F-]+)
                              /     |     \
                             /      |      \
                           url     back    element
                            |       |       |     \
                            |       |       |      5
                            2       3       |
                                        ([0-9a-fA-F-]+)

以上是您的示例树的一部分。您必须使用自定义数据结构来实现树,但这相当简单。

【讨论】:

  • 碰巧,我对这个和另一个答案采取了混合方法,但这是我缺少的洞察力。
【解决方案2】:

与其将模式中的 :session_id 和 :id 标记替换为特定值然后进行匹配,不如获取候选者并在它们上使用正则表达式替换以将特定值替换为占位符(session_id 和 id)?然后就可以直接在map中查找泛化字符串了。

【讨论】:

  • 与该方法相关的两个挑战。首先,“sessionid”和“id”不是唯一可以出现在 URL 中这些位置的标记名称;示例 URL 只是使它看起来如此。其次,令牌值是十六进制编码的,因此它们也可能包含字母字符。我已经编辑了问题和示例代码以使其更加清晰。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多