首页 > 解决方案 > std::smatch str() 没有返回正确的字符串

问题描述

我决定制作自己的 regex.h,其中包含一个带有一些方法的类,以便更轻松地检查和使用正则表达式解析字符串。

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

这是整个 regex.h 文件:

#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) {}

除了“match_str”方法之外的所有东西似乎都可以正常工作

这段代码:

int main() {
    regex rx("(int|long)( +)([a-z]);");
    if (rx.generate_matches("int a; int b; int c;")) {
        std::cout << rx.match_str() + "\n";
    }
    system("pause");
}

输出:

¦¦¦¦¦¦
Press any key to continue . . .

标签: c++regex

解决方案


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

您可以向您的类添加其他变量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,而不是临时对象。


推荐阅读