如何用fscanf提取html

时间:2012-10-17 22:20:33

标签: c++ scanf

我有一个文件,每行都有一个。

<div style="random properties" id="keyword1:string id:int">text</div>
<div style="random properties" id="keyword1:string id:int">text</div>
<div style="random properties" id="keyword2:string id:int">text</div>
<div style="random properties" id="keyword2:string id:int">text</div>

我可以使用fscanf返回匹配的keyword1和keyword2的文本和id列表吗?

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式阅读它:

std::string s;
std::regex r( "<div style=\"[^\"]*\" id=\".*(\\d+)\">((?:(?!</div>).)*)</div>" );
while( std::getline(in, s) ) {
    std::smatch m;
    if( std::regex_match(s, m, r) ) {
        std::cout << "id = " << m.str(1) << ", text = " << m.str(2) << std::endl;
    } else {
        std::cout << "invalid pattern" << std::endl;
    }
}

但是,如果您想了解有关regex的更多信息,请转到http://en.cppreference.com/w/cpp/regex