正则表达式及其游戏中应用

发布于:2025-05-01 ⋅ 阅读:(15) ⋅ 点赞:(0)

一、正则表达式基础知识

✅ 什么是正则表达式?

正则表达式是一种用来匹配字符串的规则表达式,常用于搜索、验证、替换等文本处理场景

比如你想找出玩家输入中的邮箱、命令、作弊码……正则就特别好用。


📚 常见语法速查表:

表达式 含义 示例
. 匹配任意字符(除换行) a.c 能匹配 abc
\d 匹配一个数字 [0-9] \d+ 匹配数字串
\w 匹配字母或数字字符(含下划线) \w+ 匹配变量名
^ 匹配字符串开始 ^hello 匹配以 hello 开头的
$ 匹配字符串结尾 end$ 匹配以 end 结尾的
* 前面的内容重复 0 次或多次 a* 匹配空、a、aa
+ 重复 1 次或多次 a+ 匹配 a、aa
{n} 恰好重复 n 次 \d{4} 匹配年份
[] 匹配字符集合 [abc] 匹配 a、b、c
` `
() 分组 (ab)+ 匹配 abab、ab

二、游戏开发中的正则应用

1️⃣ 玩家输入指令解析(命令行游戏常见)

示例: 玩家输入 /give gold 100,你可以用正则来提取命令和参数。

std::regex pattern("^/give\\s+(\\w+)\\s+(\\d+)$");
std::smatch match;
if (std::regex_match(input, match, pattern)) {
    std::string item = match[1]; // gold
    int amount = std::stoi(match[2]); // 100
}

2️⃣ 聊天系统中的敏感词过滤

std::string msg = "你个笨蛋";
std::regex badword("(笨蛋|傻瓜|死鬼)");
msg = std::regex_replace(msg, badword, "**");

输出:你个**


3️⃣ 作弊码识别

std::string code = "IDKFA"; // doom秘籍
std::regex cheatCode("^IDKFA$");
if (std::regex_match(code, cheatCode)) {
    // 激活秘籍
}

4️⃣ 玩家ID、邮箱、昵称格式验证

  • 昵称只能是英文或数字,3~10位:
std::regex namePattern("^[a-zA-Z0-9]{3,10}$");
  • 邮箱格式:
std::regex emailPattern("^[\\w.-]+@[\\w.-]+\\.\\w+$");

三、练习题部分

🧠 理论题

题 1: 正则 ^player\\d{2,4}$ 能匹配以下哪个字符串?

A. player1
B. player999
C. player00000
D. player12

✅ 答案:B、D


💻 编程题

题 2: 实现一个函数,判断用户输入是否是 /attack target_name 的命令格式。

bool isValidAttackCommand(const std::string& input) {
    std::regex pattern("^/attack\\s+\\w+$");
    return std::regex_match(input, pattern);
}

四、🎮 小游戏项目:《正则冒险者》

✨ 游戏概念:

玩家在迷宫中通过输入合法的魔法咒语(正则校验)释放技能、解锁门、开启宝箱。


📌 核心逻辑片段:

std::string input;
std::getline(std::cin, input);

std::regex openDoor("^open\\s+door(\\d+)$");
std::regex spell("^cast\\s+\\w{3,10}$");
std::regex chest("^unlock\\s+chest_(gold|silver|bronze)$");

if (std::regex_match(input, openDoor)) {
    std::cout << "你打开了一扇门!\n";
} else if (std::regex_match(input, spell)) {
    std::cout << "你释放了一个神秘法术!\n";
} else if (std::regex_match(input, chest)) {
    std::cout << "你成功打开了宝箱!\n";
} else {
    std::cout << "命令无效!请检查语法。\n";
}