You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++ std::regex匹配123.txt或456.txt?

正确的正则表达式写法

你之前用的*.txt是shell通配符的写法,并非正则表达式语法——正则里*是量词,代表匹配前面的字符0次或多次,不是“任意字符”的意思。要精准匹配"123.txt"或"456.txt",可以使用以下正则:

std::regex reg("^(123|456)\\.txt$");

语法细节说明:

  • ^:匹配字符串开头,避免匹配类似"abc123.txt"这类包含目标内容的长文本
  • (123|456):分组选择语法,指定只能匹配"123"或者"456"
  • \\.:正则中.默认匹配任意单个字符,要匹配实际的.必须转义;C++字符串里需要额外加一个反斜杠完成转义
  • $:匹配字符串结尾,避免匹配类似"123.txtabc"这类目标内容后带额外字符的文本

示例验证代码:

#include <iostream>
#include <regex>
#include <string>

int main() {
    std::regex reg("^(123|456)\\.txt$");
    std::string test1 = "123.txt";
    std::string test2 = "456.txt";
    std::string test3 = "789.txt";

    std::cout << std::boolalpha;
    std::cout << std::regex_match(test1, reg) << std::endl; // 输出true
    std::cout << std::regex_match(test2, reg) << std::endl; // 输出true
    std::cout << std::regex_match(test3, reg) << std::endl; // 输出false

    return 0;
}

如果你的需求是匹配任意数字开头的.txt文件(而非仅123和456),可以改用:

std::regex reg("^\\d+\\.txt$");

其中\\d+表示匹配一个或多个连续数字。

内容的提问来源于stack exchange,提问作者dodle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 05:16:00