std :: smatch str()没有返回正确的字符串

时间:2018-06-24 06:06:17

标签: c++ regex

我决定制作自己的regex.h,其中包含带有一些方法的类,以便更轻松地进行检查,并使用regexes解析字符串。

.h的第一个版本仅包含一些方法,这些方法工作得很好。后来,我决定将所有这些方法组织在一个类中,一切正常,但是在某些时候,“ match_str”方法开始返回正确长度的字符串,但仅包含“ |”字符,由于某种原因。

这是整个regex.h文件:

:ring {:handler your.routes.namespace/site}

一切正常,但“ match_str”方法似乎可以正常工作

此代码:

project.clj

输出:

#include <string>
#include <regex>
#include <vector>

class regex { 
    std::vector<std::smatch> match;
public: 
    regex(std::string);

    std::regex r;

    int generate_matches(std::string s) {
        auto matches_begin = std::sregex_iterator(s.begin(), s.end(), r);
        auto matches_end = std::sregex_iterator();
        for (std::sregex_iterator i = matches_begin; i != matches_end; ++i) { match.push_back(*i); }
        return match.size();
    }

    bool matches(std::string s) {
        return std::regex_search(s, r);
    }

    int match_count() {
        return match.size();
    }

    std::string match_str(int index = 0, int group = 0) {
        return match.size() ? match.at(index)[group].str() : "";
    }

    int match_pos(int index = 0) {
        return match.at(index).position() + 1;
    }
}; regex::regex(std::string regex) : r(regex) {}

1 个答案:

答案 0 :(得分:4)

match_results的对象保留指向匹配字符串的const iteratorconst char*指针。在generate_matches字符串s中,对象是局部变量,因此在函数终止时将其删除,您无法将const迭代器或局部变量的指针存储到vector-您将有悬空的指针,当您执行操作时,它是未定义的行为尝试读取被破坏的物体的数据。

您可以在regex类中添加其他变量,并按如下所示更改generate_matches函数:

class regex { 
  std::vector<std::smatch> match;
  std::string str; // <---

int generate_matches(std::string s) {
    str = s; // <---
    auto matches_begin = std::sregex_iterator(str.begin(), str.end(), r); // <--- 
    auto matches_end = std::sregex_iterator();
    for (std::sregex_iterator i = matches_begin; i != matches_end; ++i) { match.push_back(*i); }
    return match.size();
}

现在您可以调用match_str函数并读取match向量,因为smatch对象引用现有对象-str,不是临时的。