在C++中,使用正则表达式匹配字符串主要依赖 <regex> 库,需包含头文件并使用 std 命名空间。以下是具体方法及示例:
1. 包含头文件与命名空间#include <regex>#include <string>#include <iostream>using namespace std; // 简化代码2. 完全匹配:std::regex_match- 功能:判断整个字符串是否完全符合正则模式。
- 示例:匹配纯数字字符串。
string str = "12345";regex pattern(R"(d+)"); // 原始字符串避免转义,匹配一个或多个数字if (regex_match(str, pattern)) { cout << "完全匹配成功" << endl; // 输出:完全匹配成功}- 注意:仅当整个字符串匹配时返回 true。例如 "123abc" 不会被 d+ 完全匹配。
3. 部分匹配:std::regex_search- 功能:在字符串中查找符合模式的子串。
- 示例1:提取字符串中的数字。
string text = "age: 25, name: Tom";regex pat(R"(d+)"); // 匹配数字smatch matches; // 存储匹配结果if (regex_search(text, matches, pat)) { cout << "找到数字: " << matches[0] << endl; // 输出:找到数字: 25}4. 提取捕获组- 功能:通过括号 () 定义捕获组,提取特定部分。
- 示例:从字符串中提取邮箱地址。
string input = "email: john@example.com";regex email_pattern(R"(email:s*([a-z]+@[a-z]+.[a-z]+))");smatch result;if (regex_search(input, result, email_pattern)) { cout << "完整匹配: " << result[0] << endl; // 输出:email: john@example.com cout << "提取邮箱: " << result[1] << endl; // 输出:john@example.com}5. 常用正则表达式模式- d+:匹配一个或多个数字(如 "123")。
- [a-zA-Z]+:匹配一个或多个字母(如 "abc" 或 "XYZ")。
- w+@w+.w+:简单匹配邮箱格式(如 "user@example.com")。
- ^d{3}-d{3}-d{4}$:匹配电话号码(如 "123-456-7890")。
6. 原始字符串(推荐)- 作用:避免正则表达式中的转义问题(如 d 无需写成 d)。
- 语法:使用 R"(...)" 包裹模式。
regex pattern(R"(d+)"); // 等价于 regex pattern("d+");完整示例代码#include <regex>#include <string>#include <iostream>using namespace std;int main() { // 完全匹配示例 string str = "12345"; regex num_pattern(R"(d+)"); if (regex_match(str, num_pattern)) { cout << "完全匹配成功: " << str << endl; } // 部分匹配示例 string text = "age: 25, name: Tom"; regex digit_pattern(R"(d+)"); smatch matches; if (regex_search(text, matches, digit_pattern)) { cout << "找到数字: " << matches[0] << endl; } // 捕获组示例 string input = "email: john@example.com"; regex email_pattern(R"(email:s*([a-z]+@[a-z]+.[a-z]+))"); smatch result; if (regex_search(input, result, email_pattern)) { cout << "完整匹配: " << result[0] << endl; cout << "提取邮箱: " << result[1] << endl; } return 0;}总结- 完全匹配:用 regex_match,要求整个字符串符合模式。
- 部分匹配:用 regex_search,可提取子串或捕获组。
- 捕获组:通过括号 () 定义,用 smatch[1]、smatch[2] 等获取。
- 原始字符串:推荐使用 R"(...)" 避免转义。
掌握以上方法后,可高效处理C++中的字符串匹配需求。