简体   繁体   English

在c ++正则表达式上需要帮助

[英]need help on c++ Regex

I try to make following code work for my gcc 4.8.1 but i can't . 我尝试使以下代码适用于我的gcc 4.8.1,但我做不到。 if you need more information ,let me know. 如果您需要更多信息,请告诉我。 thank you so much 非常感谢

std::cmatch res;
std::string str = "<h2>I'm a piece of text</h2>";
std::regex rx("<h(.)>([^<]+)");
std::regex_search(str.c_str(), res, rx);
std::cout << res[1] << ". " << res[2] << "\n";

output: 输出:

2. Egg prices

according to chris, i need to wait gcc 4.9. 根据克里斯,我需要等待海湾合作委员会4.9。 if that, how does you implement this design in current gcc(not boost)? 如果那样,您如何在当前gcc(而不是boost)中实现此设计? i want to Retrieve matches 我想检索比赛

Thanks again. 再次感谢。

As per the error message, you gotta use another library, for example Boost.Regex 根据错误消息,您必须使用另一个库,例如Boost.Regex

If you want to sanitize HTML you should consider using a more specialized technique. 如果要清理HTML,则应考虑使用更专业的技术。 I personally do it through jsoup . 我个人通过jsoup做到这一点。 Gumbo might work for C++. Gumbo可能适用于C ++。 Also an XML parser will usually work. XML解析器通常也可以使用。

I don´t have a boost env now to test (I´ll do it ASAP), but if you have, try something like: 我现在没有增强环境来测试(我会尽快进行),但是如果您有,请尝试以下方法:

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

int main(){

try{
  std::string str("<h2>I'm a piece of text</h2>");

  boost::regex rx("(<h[1-9]>)(.*)(<\\/h[1-9]>)");
  boost::sregex_iterator it(str.begin(), str.end(), rx);

  std::cout << << (*it)[1] << "\n"; // get group 1

 return 0;
}

Regex 101 is an excelent source to validade your regex! 正则表达式101是验证您的正则表达式的绝佳来源!

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

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