从Telegram bot更新中剥离表情符号

时间:2016-11-03 04:01:47

标签: boost unicode c++03 boost-regex boost-propertytree

我想从使用boost属性树解析的json Telegram bot更新中删除表情符号

我尝试使用此答案中的正则表达式模式和其他一些但我不确定如何让它们在C ++中工作(下面会导致崩溃): https://stackoverflow.com/a/24674266/2212021

"message":{
   "message_id":123,
   "from":{
      "id":12345,
      "first_name":"name",
      "username":"username"
   },
   "chat":{
      "id":12345,
      "first_name":"name",
      "username":"username",
      "type":"private"
   },
   "date":1478144459,
   "text":"this is \ud83d\udca9 a sentence"
}
BOOST_FOREACH(const boost::property_tree::ptree::value_type& child, jsontree.get_child("result"))
{

        std::string message(child.second.get<std::string>("message.text").c_str());

        boost::regex exp("/[\u{1F600}-\u{1F6FF}]/");
        std::string message_clean = regex_replace(message, exp, "");

        ...
}
  

在0x00007FF87C1C7788处抛出异常   CrysisWarsDedicatedServer.exe:Microsoft C ++异常:   boost :: exception_detail :: clone_impl&gt;在内存位置0x000000001003F138。 CrysisWarsDedicatedServer.exe中0x00007FF87C1C7788处的未处理异常:Microsoft C ++   例外:   boost :: exception_detail :: clone_impl&gt;在内存位置0x000000001003F138。

1 个答案:

答案 0 :(得分:1)

第一个问题是在具有任意文本编码的字节数组上使用.c_str()。没有必要,所以不要这样做。

接下来,'\u'不是有效的C ++字符转义符。您的意思是'\\u'吗?

最后,确保Boost Regex为compiled with Unicode support并使用相应的函数。

花了一些时间阅读这些文档页面以及

我想出了

<强> Live On Wandbox

//#define BOOST_HAS_ICU
#include <boost/property_tree/json_parser.hpp>
#include <boost/regex.hpp>
#include <boost/regex/icu.hpp>
#include <iostream>
std::string asUtf8(icu::UnicodeString const& ustr);

std::string sample = R"(
{
    "message":{
       "message_id":123,
       "from":{
          "id":12345,
          "first_name":"name",
          "username":"username"
       },
       "chat":{
          "id":12345,
          "first_name":"name",
          "username":"username",
          "type":"private"
       },
       "date":1478144459,
       "text":"this is \ud83d\udca9 a sentence"
    }
}
)";

int main() {

    boost::property_tree::ptree pt;
    {
        std::istringstream iss(sample);
        read_json(iss, pt);
    }
    auto umessage       = icu::UnicodeString::fromUTF8(pt.get("message.text", ""));
    boost::u32regex exp = boost::make_u32regex("\\p{So}");

    auto clean = boost::u32regex_replace(umessage, exp, UnicodeString::fromUTF8("<symbol>"));

    std::cout << asUtf8(clean) << "\n";
}

std::string asUtf8(icu::UnicodeString const& ustr) {
    std::string r;
    {
        icu::StringByteSink<std::string> bs(&r);
        ustr.toUTF8(bs);
    }

    return r;
}

打印:

this is <symbol> a sentence