gpt4 book ai didi

c++ - 从消息中检索字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:55:58 25 4
gpt4 key购买 nike

我正在为 Crysis Wars 进行我的第一个公共(public)服务器修改,为了确保没有人窃取我的代码,我将尽可能多地放在基于 C++ 的 DLL 中(替代方案是 Lua)。为此,我必须将命令放入 DLL 中,其中一些命令需要额外的变量。这是一个例子:

!ban [玩家名] [时间] [原因]

我将如何检索变量 playername、time 和 reason,所有这些变量都有不同的字符长度?原因变量也可能有多个单词(例如“冒犯性信息和欺骗”)需要被提取。

在 Lua 中,这将通过一个简单的“string.match”来完成;我想我总是可以在 Lua 中进行消息排序,然后将其发送回 C++,但这可能会导致整个聊天命令系统困惑。

它需要从“const char *msg”中提取变量,系统会在发送的每条消息中对其进行分析。我已经分析了它的命令消息(以“!”开头的消息)。执行此操作的最佳方法是什么?

示例:!ban Con 5 spam- 这将踢玩家“Confl!ct”(我已经有部分扫描码来识别部分名称)五分钟

!ban Con spam- 这将永久禁止玩家“Confl!ct”

最佳答案

这里的方法是使用正则表达式,又名 regex。当我回顾我的老问题,使它们变得聪明时,我很快使用了 txt2re准备一个快速的正则表达式食谱,如下所示:

#include <stdlib.h>
#include <string>
#include <iostream>
#include <pme.h>

int main()
{
std::string txt="!ban command variables";

std::string re1=".*?"; // Non-greedy match on filler
std::string re2="((?:[a-z][a-z]+))"; // Word 1
std::string re3=".*?"; // Non-greedy match on filler
std::string re4="((?:[a-z][a-z]+))"; // Word 2
std::string re5=".*?"; // Non-greedy match on filler
std::string re6="((?:[a-z][a-z]+))"; // Word 3

PME re(re1+re2+re3+re4+re5+re6,"gims");
int n;
if ((n=re.match(txt))>0)
{
std::string word1=re[1].c_str();
std::string word2=re[2].c_str();
std::string word3=re[3].c_str();
std::cout << "("<<word1<<")"<<"("<<word2<<")"<<"("<<word3<<")"<< std::endl;
}
}

此代码需要这些库,因为默认情况下 C++ 不包含正则表达式函数:

关于c++ - 从消息中检索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19011853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com