正则表达式使用regex_search获取各种结果

时间:2012-03-22 13:35:57

标签: c++ regex

我只想获取给定字符串的结果

#include <regex>
#include <iostream>
#include <string>

#include <conio.h>
using namespace std;

int main () {
   std::tr1::cmatch res;
   string str;
   str = "a lot of unknown text here<h2>Test2 12</h2> a lot of unknown text here <h2>Test3 45</h2>a lot of text here too";
   std::tr1::regex rx("Test(\d+) (\\d+)");
   std::tr1::regex_search(str.c_str(), res, rx);
   std::cout << "RES 1: " << res[1] << ". " << res[2] << "\n";
   std::cout << "RES 2: " <<  res[3] << ". " << res[4] << "\n";
   return 0;
}

我希望它能够从一次搜索得到两者的结果,例如:

  

数组1:[1] = 2,[2] = 12和   数组2:[1] = 3,[2] = 45或者它可能是这样的:[1] = 2,[2] = 12,[3] = 3,[4] = 45

我该怎么做?如果我使用的功能不正确,请告诉我哪个功能以及如何使用它来执行我在此处所要求的功能。 我希望我很清楚, 提前谢谢。

1 个答案:

答案 0 :(得分:2)

您正在寻找的是regex_iterator类模板。在您的示例中:

#include <regex>
#include <iostream>
#include <string>

int main () {
    std::string str("a lot of unknown text here<h2>Test2 12</h2> a lot of unknown text here <h2>Test3 45</h2>a lot of text here too");
    std::tr1::regex rx("Test(\\d+) (\\d+)");
    std::tr1::sregex_iterator first(str.begin(), str.end(), rx);
    std::tr1::sregex_iterator last;

    for (auto it = first; it != last; ++it) 
    {
        std::cout << "[1]=" << it->str(1) << " [2]=" << it->str(2) << std::endl;
    }

    return 0;
}

此外,您可以使用regex_token_iterator类模板实现您的选项编号2:

#include <regex>
#include <iostream>
#include <string>

int main () 
{
    std::string str("a lot of unknown text here<h2>Test2 12</h2> a lot of unknown text here <h2>Test3 45</h2>a lot of text here too");
    std::tr1::regex rx("Test(\\d+) (\\d+)");
    int fields[2] = { 1, 2 };
    std::tr1::sregex_token_iterator first(str.begin(), str.end(), rx, fields);
    std::tr1::sregex_token_iterator last;

    std::size_t i = 0;
    for (auto it = first; it != last; ++it) 
    {
        std::cout << "[" << i << "]=" << it->str() << std::endl;
        ++i;
    }

    return 0;
}