2012-05-01 34 views
1

我想在一个字符串中做两个替换,并且我知道如何在php中编写正则表达式,但我不熟悉C++ boost。如何在C++ boost中编写这些正则表达式?

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

如何在C++ boost中编写代码?

在此先感谢。

+3

嗯,你尝试了吗?你得到什么错误/问题? – Mat

+0

这些正则表达式可以正常工作,但是您需要将您的正则表达式转义字符加倍转义(例如,\ r应该是\\ r),因为\也恰好是C++中的字符串转义字符。 – Benj

+0

我使用了双转义字符并试过,但它并没有取代任何东西... – luyi0619

回答

1

适用所有常用的warnings about parsing HTML with regexes

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

int main() 
{ 
    boost::regex double_br("<br/?>[ \\r\\n\\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 << ":\n"; 

    std::string result; 
    result = boost::regex_replace(*s, double_br, "</p><p>"); 
    result = boost::regex_replace(result, fonts, ""); 

    std::cout << " - [" << result << "]\n"; 
    } 

    return 0; 
} 

输出:

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]