开发者

How do I get the regex matched value using Boost.Regex?

I'm trying to extract the domain from a URL. Following is an example script.

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main () {

  std::string url = "http://mydomain.com/randompage.php";
  boost::regex exp("开发者_JAVA百科^https?://([^/]*?)/");
  std::cout << regex_search(url,exp);

}

How do I print the matched value?


You need to use the overload of regex_search that takes a match_results object. In your case:

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main () {    
  std::string url = "http://mydomain.com/randompage.php";
  boost::regex exp("^https?://([^/]*?)/");
  boost::smatch match;
  if (boost::regex_search(url, match, exp))
  {
    std::cout << std::string(match[1].first, match[1].second);
  }    
}

Edit: Corrected begin, end ==> first, second

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜