在 Linux 环境下使用 C++ 进行正则表达式匹配,主要依赖于 <regex>
头文件,该头文件自 C++11 起引入。以下是使用正则表达式进行匹配的基本步骤和示例代码:
<regex>
头文件。std::regex
定义一个正则模式。std::regex_match
检查整个字符串是否完全匹配正则表达式。std::regex_search
在字符串中查找匹配的部分。以下是一个简单的示例,演示如何使用正则表达式在 C++ 中进行匹配:
#include <iostream>
#include <string>
#include <regex>
int main() {
// 要匹配的字符串
std::string text = "联系电话: 138-0011-0022";
// 定义正则表达式模式
// 解释:
// \d{3} : 三位数字
// - : 连字符
// \d{4} : 四位数字
// - : 连字符
// \d{4} : 四位数字
std::regex pattern(R"(\d{3}-\d{4}-\d{4})");
// 使用 regex_match 检查整个字符串是否匹配
if (std::regex_match(text, pattern)) {
std::cout << "整个字符串匹配成功!" << std::endl;
} else {
std::cout << "整个字符串匹配失败。" << std::endl;
}
// 使用 regex_search 查找字符串中的第一个匹配部分
std::smatch matches;
if (std::regex_search(text, matches, pattern)) {
std::cout << "找到匹配部分: " << matches.str() << std::endl;
// 输出所有捕获组(如果有)
for (size_t i = 0; i < matches.size(); ++i) {
std::cout << "捕获组 "<< i << ": " << matches[i] << std::endl;
}
} else {
std::cout << "未找到匹配部分。" << std::endl;
}
return 0;
}
确保使用支持 C++11 或更高版本的编译器进行编译。例如,使用 g++
:
g++ -std=c++11 -o regex_example regex_example.cpp
./regex_example
整个字符串匹配成功!
找到匹配部分: 138-0011-0022
捕获组 0: 138-0011-0022
捕获组 1: 138
捕获组 2: 0011
捕获组 3: 0022
字符类:
\d
:数字(等价于 [0-9]
)\w
:字母、数字或下划线(等价于 [A-Za-z0-9_]
)\s
:空白字符量词:
*
:零次或多次+
:一次或多次?
:零次或一次{n}
:精确 n 次{n,}
:至少 n 次{n,m}
:n 到 m 次边界匹配:
^
:字符串开头$
:字符串结尾\b
:单词边界分组与捕获:
()
进行分组和捕获。C++11 支持命名捕获组,可以通过 (?<name>...)
语法实现:
std::regex pattern(R"((?<area_code>\d{3})-(?<first_part>\d{4})-(?<second_part>\d{4}))");
std::smatch matches;
if (std::regex_search(text, matches, pattern)) {
std::cout << "区号: " << matches["area_code"] << std::endl;
std::cout << "前四位: " << matches["first_part"] << std::endl;
std::cout << "后四位: " << matches["second_part"] << std::endl;
}
使用 std::regex_replace
进行字符串替换:
std::string replacement = "$1-$2"; // 将匹配的部分替换为区号-前四位
std::string replaced_text = std::regex_replace(text, pattern, replacement);
std::cout << "替换后的字符串: " << replaced_text << std::endl;
正则表达式操作可能会抛出异常,如 std::regex_error
,应进行适当的异常处理:
try {
std::regex invalid_pattern("[");
} catch (const std::regex_error& e) {
std::cerr << "正则表达式错误: " << e.what() << std::endl;
}
\
是转义字符,因此在定义正则表达式时,需要对反斜杠进行双重转义,例如 \\d
表示 \d
。<regex>
是从 C++11 开始引入的。通过以上步骤和示例,您可以在 Linux 环境下使用 C++ 进行基本的正则表达式匹配和操作。根据具体需求,您可以进一步探索正则表达式的更多功能和高级用法。