
在C++中使用正则表达式需要包含头文件 <regex>,通过 std::regex 相关类来实现字符串匹配。C++11 起引入了原生支持的正则功能,常用类包括:std::regex、std::smatch、std::regex_match 和 std::regex_search。
std::regex_match 用于判断整个字符串是否完全匹配指定正则表达式。
示例:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "hello123";
std::regex pattern(R"([a-zA-Z]+\d+)"); // 匹配字母后跟数字
if (std::regex_match(str, pattern)) {
std::cout << "完全匹配!" << std::endl;
} else {
std::cout << "不匹配。" << std::endl;
}
return 0;
}
只有当整个字符串符合模式时才返回 true。
立即学习“C++免费学习笔记(深入)”;
std::regex_search 用于查找字符串中是否存在与正则匹配的子串。
示例:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "abc hello123 world";
std::regex pattern(R"([a-zA-Z]+\d+)");
std::smatch match;
if (std::regex_search(str, match, pattern)) {
std::cout << "找到匹配内容:" << match.str() << std::endl;
}
return 0;
}
match 是一个 std::smatch 对象,可以提取出匹配的子字符串。
使用括号 () 定义捕获组,可以从匹配结果中提取特定部分。
示例:提取用户名和域名
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string email = "contact@example.com";
std::regex pattern(R"(([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,}))");
std::smatch match;
if (std::regex_search(email, match, pattern)) {
std::cout << "用户名: " << match[1].str() << std::endl;
std::cout << "域名: " << match[2].str() << std::endl;
}
return 0;
}
match[0] 是完整匹配,match[1]、match[2] 分别对应第一个和第二个捕获组。
基本上就这些。注意正则表达式字符串建议使用原始字符串字面量 R"(...)",避免转义问题。c++ regex 功能强大但性能一般,频繁使用时可考虑缓存 regex 对象。不复杂但容易忽略细节,比如全匹配和部分匹配的区别。基本上就这些。
以上就是c++++正则表达式regex怎么匹配字符串_c++ regex匹配方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号