答案是使用C++11的<regex>库进行正则匹配。需包含头文件<regex><string><iostream>,用std::regex_match判断字符串是否完全匹配,如验证纯数字字符串。

在C++中使用正则表达式,需要借助标准库中的 <regex> 头文件。从 C++11 开始,std::regex 提供了对正则表达式的完整支持,包括匹配、搜索、替换和迭代等功能。
#include <regex>
#include <string>
#include <iostream>
通常还会使用 std 命名空间来简化代码:
using namespace std;
立即学习“C++免费学习笔记(深入)”;
示例:验证一个字符串是否为纯数字
std::string str = "12345";
std::regex re(R"(d+)"); // 匹配一个或多个数字
if (std::regex_match(str, re)) {
std::cout }
R"(d+)" 是原始字符串字面量,避免转义字符问题。
示例:查找字符串中是否有邮箱格式片段
std::string text = "联系我 at example@email.com";
std::regex email_re(R"(w+@w+.w+)");
std::smatch match; // 用于保存匹配结果
if (std::regex_search(text, match, email_re)) {
std::cout }
match[0] 表示完整匹配的内容,如果有分组,可用 match[1], match[2] 等获取。
示例:提取日期中的年月日
std::string date_str = "2023-12-25";
std::regex date_re(R"((d{4})-(d{2})-(d{2}))");
std::smatch result;
if (std::regex_match(date_str, result, date_re)) {
std::cout }
示例:将多个空格替换为单个空格
std::string input = "too many spaces";
std::regex space_re("\s+");
std::string cleaned = std::regex_replace(input, space_re, " ");
std::cout
基本上就这些。掌握 regex_match、regex_search 和 regex_replace 这三个核心函数,再配合常用正则语法,就能处理大多数文本匹配任务。注意编译时需启用 C++11 或更高标准。不复杂但容易忽略细节,比如转义和原始字符串的使用。
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号