如何在C ++中获取std :: string的基本preg_match_all替换?

时间:2010-02-01 15:26:53

标签: c++ regex string stdstring

带有“basic”的

表示:只有运算符“+”( - > follow ..)和“|” ( - >或者)是必需的。

原型:

preg_match_all(std::string pattern, std::string subject, std::vector<std::string> &matches)

用法示例:

std::vector<std::string> matches;
std::string pattern, subject;
subject = "Some text with a lots of foo foo and " +  char(255) + " again " + char(255);
pattern = "/" + char(255) + char(255) + "+|foo+/";
preg_match_all(pattern, subject, matches);

之后的比赛应通过matches[n]提供。是否有人使用提升和/或PCRE提示没有?如果没有,我是如何通过提升来实现的?

3 个答案:

答案 0 :(得分:2)

这将返回所有匹配的向量及其找到的索引。

std::vector<std::pair<std::string, unsigned int>> RegexPP::MatchAll(std::string pattern, std::string haystack) {
    std::vector<std::pair<std::string, unsigned int>> matches;

    std::regex p(pattern);

    std::sregex_iterator start(haystack.begin(), haystack.end(), p), end;

    for(; start != end; start++) {
        auto match = *start; // dereference the iterator to get the match_result
        matches.push_back(std::pair<std::string, unsigned int>(match.str(), match.position()));
    }

    return matches;
}

答案 1 :(得分:0)

您可以使用std::string::find汇总某些内容,通过仿函数进行匹配,并将结果推送到字符串向量。

它在boost中的实现方式可能对你想要的东西有点过分 - 你首先需要将表达式分解为lexems,然后编译一个状态机来解析给定的正则表达式。

答案 2 :(得分:0)