【2024|第15代版本Linux C/C++全栈开发合集(职场常用/面试常问技术点+项目实战)】
C++11引入了正则表达式支持,使得C++标准库可以处理字符串模式匹配和搜索。C++标准库中的正则表达式功能集中在<regex>头文件中,主要包含以下几个核心类和函数:
核心类和函数
std::regex:表示一个正则表达式对象,用于模式匹配。std::smatch和std::cmatch:分别用于存储字符串(std::string)和C风格字符串(const char*)的匹配结果。std::regex_search:在输入序列中搜索正则表达式的匹配。std::regex_match:检测整个输入序列是否匹配正则表达式。std::regex_replace:使用正则表达式替换输入序列中的子字符串。
常用方法和用法
1. std::regex
正则表达式的定义和使用:
#include <iostream>
#include <regex>
int main() {
std::string pattern = R"(\d+)";
std::regex re(pattern);
return 0;
}
R"(\d+)" 是一个原始字符串文字,避免了反斜杠转义的问题。
2. std::regex_match
用于检查整个字符串是否匹配给定的正则表达式:
#include <iostream>
#include <regex>
int main() {
std::string s = "12345";
std::regex re(R"(\d+)");
if (std::regex_match(s, re)) {
std::cout << "The entire string is a number.\n";
} else {
std::cout << "The string is not a number.\n";
}
return 0;
}
3. std::regex_search
用于在字符串中搜索正则表达式的匹配:
#include <iostream>
#include <regex>
int main() {
std::string s = "Hello 123 World";
std::regex re(R"(\d+)");
std::smatch match;

最低0.47元/天 解锁文章
3583

被折叠的 条评论
为什么被折叠?



