从 Telegram 机器人更新中删除表情符号

Strip emojis from Telegram bot update

我想从使用 boost 属性 树

解析的 json Telegram 机器人更新中删除表情符号

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

"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, "");

        ...
}

Exception thrown at 0x00007FF87C1C7788 in CrysisWarsDedicatedServer.exe: Microsoft C++ exception: boost::exception_detail::clone_impl > at memory location 0x000000001003F138. Unhandled exception at 0x00007FF87C1C7788 in CrysisWarsDedicatedServer.exe: Microsoft C++ exception: boost::exception_detail::clone_impl > at memory location 0x000000001003F138.

第一个问题是在具有任意文本编码的字节数组上使用 .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