C++正则表达式实战:从入门到精通,面试必考的文本处理技巧全解析
引言
正则表达式是C++程序员的文本处理利器,也是大厂面试的高频考点。从数据验证到日志解析,正则表达式无处不在。本文将从基础语法出发,深入讲解C++11正则表达式库的使用方法,并通过实战案例帮你掌握这个强大工具。
一、正则表达式基础
1.1 什么是正则表达式
正则表达式(Regular Expression)是一种文本模式匹配工具,用于描述字符串的匹配规则。
| 特性 | 说明 |
|---|---|
| 模式匹配 | 查找符合规则的文本 |
| 文本提取 | 从文本中提取特定内容 |
| 文本替换 | 替换符合规则的内容 |
| 文本验证 | 验证文本格式是否正确 |
1.2 基础语法
| 语法 | 说明 | 示例 |
|---|---|---|
. | 匹配任意字符(除换行) | a.c匹配 abc, axc |
* | 匹配0次或多次 | ab*c匹配 ac, abc, abbc |
+ | 匹配1次或多次 | ab+c匹配 abc, abbc |
? | 匹配0次或1次 | ab?c匹配 ac, abc |
^ | 匹配开头 | ^abc匹配以abc开头 |
$ | 匹配结尾 | abc$匹配以abc结尾 |
[] | 字符集合 | [abc]匹配a或b或c |
[^] | 排除集合 | [^abc]匹配非a非b非c |
() | 分组 | (abc)+匹配abc一次或多次 |
| ` | ` | 或 |
\d | 数字 | \d+匹配一个或多个数字 |
\w | 单词字符 | \w+匹配字母数字下划线 |
\s | 空白字符 | \s+匹配空格制表符等 |
二、C++ regex库
2.1 核心类
#include<iostream>#include<regex>#include<string>intmain(){// 创建正则表达式对象std::regexpattern("\\d+");// 匹配数字// 检查是否匹配std::string text="abc123def456";if(std::regex_search(text,pattern)){std::cout<<"找到数字"<<std::endl;}return0;}2.2 regex_match:全匹配
#include<iostream>#include<regex>#include<string>intmain(){std::regexemailRegex("^[\\w.]+@[\\w]+\\.[\\w]+$");std::string email1="test@example.com";std::string email2="invalid-email";if(std::regex_match(email1,emailRegex)){std::cout<<email1<<" 是有效邮箱"<<std::endl;}if(!std::regex_match(email2,emailRegex)){std::cout<<email2<<" 是无效邮箱"<<std::endl;}return0;}2.3 regex_search:搜索匹配
#include<iostream>#include<regex>#include<string>intmain(){std::regexphoneRegex("\\d{3}-\\d{4}-\\d{4}");std::string text="我的电话是138-1234-5678,备用电话是139-8765-4321";std::smatch match;std::string::const_iterator