简体   繁体   English

如何在字符串中找到与boost正则表达式匹配的索引?

[英]How can I find the index in a string that matches a boost regex?

如何在字符串中找到与boost正则表达式匹配的索引?

Use the position member function of the match_results : 使用match_resultsposition成员函数:

int find_match_offset(std::string const& string_to_search,
                      boost::regex const& expression)
{
    boost::smatch results;
    if(boost::regex_match(string_to_search,results,expression))
    {
        return results.position()
    }
    return -1;
}

If you use boost::regex_match it's the whole string that's matching. 如果你使用boost :: regex_match,它就是匹配的整个字符串。
Maybe you mean to use regex_search: 也许你的意思是使用regex_search:

void index(boost::regex& re,const std::string& input){
    boost::match_results<std::string::const_iterator> what;
    boost::match_flag_type flags = boost::match_default;
    std::string::const_iterator s = input.begin();
    std::string::const_iterator e = input.end();
    while (boost::regex_search(s,e,what,re,flags)){
        std::cout << what.position() << std::endl;
        std::string::difference_type l = what.length();
        std::string::difference_type p = what.position();
        s += p + l;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM