douyan4243 2012-05-01 12:46
浏览 32
已采纳

如何在c ++ boost中编写这些正则表达式?

I want to do two replacement in a string, and i know how to write the regex in php, curently i am not familiar with c++ boost.

// Replace all doubled-up <BR> tags with <P> tags, and remove fonts.
    $string = preg_replace("/<br\/?>[ 
\s]*<br\/?>/i", "</p><p>", $string);
    $string = preg_replace("/<\/?font[^>]*>/i", "", $string);

how to write the code in c++ boost?

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • duanjiong2021 2012-05-01 14:47
    关注

    All the usual warnings about parsing HTML with regexes apply.

    #include <boost/regex.hpp>
    #include <iostream>
    #include <string>
    
    int main()
    {
      boost::regex double_br("<br/?>[ \\
    \\s]*<br/?>", boost::regex::icase);
      boost::regex fonts("</?font[^>]*>", boost::regex::icase);
    
      std::string cases[] = {
        "foo<br><br>bar",
        "one<br/><br>two",
        "a<br>   <br/>b",
        "a<br><br>c<br/><br/>d",
        "<font attr=\"value\">w00t!</font>",
        "<font attr=\"value\">hello</font><font>bye</font>",
        ""
      };
    
      for (std::string *s = cases; *s != ""; ++s) {
        std::cout << *s << ":
    ";
    
        std::string result;
        result = boost::regex_replace(*s, double_br, "</p><p>");
        result = boost::regex_replace(result, fonts, "");
    
        std::cout << "  - [" << result << "]
    ";
      }
    
      return 0;
    }
    

    Output:

    foo<br><br>bar:
      - [foo</p><p>bar]
    one<br/><br>two:
      - [one</p><p>two]
    a<br>   <br/>b:
      - [a</p><p>b]
    a<br><br>c<br/><br/>d:
      - [a</p><p>c</p><p>d]
    <font attr="value">w00t!</font>:
      - [w00t!]
    <font attr="value">hello</font><font>bye</font>:
      - [hellobye]
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀