C++11 引入了 <regex>
标准库,用于处理正则表达式。这个库提供了一系列类和函数,使得在 C++ 中进行复杂的字符串匹配、搜索和替换操作变得更加方便和高效。正则表达式是一种强大的文本处理工具,广泛应用于数据验证、文本分析和模式匹配等领域。
正则表达式是一种使用单个字符串来描述、匹配一系列符合某个句法规则的字符串的模式。在 C++ 中,正则表达式通过 <regex>
库实现。
正则表达式组成
字符类: 如 [abc] 表示匹配 a、b 或 c 中的任意一个字符。
量词: 如 *(零次或多次)、+(一次或多次)、?(零次或一次)。
边界匹配:如 ^(行的开始)、$(行的结束)。
分组: 使用圆括号 () 来创建一个分组。
C++ <regex> 库的主要类和函数
std::regex:表示一个正则表达式对象。
std::regex_match:检查整个字符串是否与正则表达式完全匹配。
std::regex_search:在字符串中搜索与正则表达式匹配的部分。
std::regex_replace:用指定的字符串替换与正则表达式匹配的部分。
std::smatch:用于存储标准字符串(std::string)的匹配结果。
std::cmatch:用于存储 C 风格字符串(const char*)的匹配结果。
std::regex_iterator:用于迭代字符串中所有匹配正则表达式的部分。
示例:
匹配整个字符串
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "Hello, World!";
std::regex pattern("^Hello, World!$");
if (std::regex_match(str, pattern)) {
std::cout << "The string matches the pattern." << std::endl;
} else {
std::cout << "The string does not match the pattern." << std::endl;
}
return 0;
}
搜索字符串中的匹配部分
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "The quick brown fox jumps over the lazy dog.";
std::regex pattern("\\b\\w{4}\\b"); // 匹配四个字母的单词
std::smatch match;
while (std::regex_search(str, match, pattern)) {
std::cout << "Found: " << match.str() << std::endl;
str = match.suffix(); // 搜索剩余的字符串
}
return 0;
}
替换匹配的部分
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "The quick brown fox jumps over the lazy dog.";
std::regex pattern("\\b\\w{4}\\b"); // 匹配四个字母的单词
std::string replacement = "****";
std::string result = std::regex_replace(str, pattern, replacement);
std::cout << "Replaced string: " << result << std::endl;
return 0;
}
使用 std::regex_iterator 迭代匹配结果
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "abc def ghi abc";
std::regex pattern("abc");
auto begin = std::sregex_iterator(str.begin(), str.end(), pattern);
auto end = std::sregex_iterator();
for (std::sregex_iterator i = begin; i != end; ++i) {
std::smatch match = *i;
std::cout << "Found: " << match.str() << std::endl;
}
return 0;
}