2017-04-01 45 views
-1

我想獲取在C + + HREF的值,但我的代碼沒有得到所需的結果如何使用正則表達式獲取C++中的href值?

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


int main() 
{ 

    std::regex url("/.*(href=')(.*)('>)/"); 
    std::string url_test = "hjsh.ppt"; 
    std::ifstream file("in.txt"); 
    if (!file.is_open()) 
    { 
     std::cerr << "Failed to open file!\n"; 
     return -1; 
    } 


    const std::string needle = "href"; 


    while (std::getline(file, url_test)) 
    { 
     if (url_test.find(needle) != std::string::npos) 
     { 
      if(regex_match(url_test, url)){} 
      std::cout << url_test << "\n"; 

     } 
    } 
} 

上述代碼打印整行作爲

<a href="11_custom_io.ppt">Ch11: Customizing I/O</a> 

我想只11_custom_io.ppt,文件的名稱。 請幫助。

+0

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454 #1732454 – 2017-04-01 14:24:48

回答

0

正如已經在評論中提到的那樣,使用正則表達式來解析XML或HTML並不是一個好主意。但是,如果你想獲得次比賽,那麼你可以使用std::match_results。例如:

std::string line("<a href='11_custom_io.ppt'>Ch11: Customizing I/O</a>"); 
std::regex re("href='(.*)'>"); 
std::smatch match; 

if (std::regex_search(line, match, re)) { 
    std::cout << "sub-match " << match[1].str() << '\n'; 
} 

輸出將是:sub-match 11_custom_io.ppt