c++ 正则表达式怎么用 c++ regex库匹配实例

admin 百科 12
C++中使用正则需包含头文件,自C++11起支持std::regex库,可用于模式匹配、搜索和替换;例如用std::regex_match验证邮箱格式合法性。

c++ 正则表达式怎么用 c++ regex库匹配实例-第1张图片-佛山资讯网

在C++中使用正则表达式需要包含 头文件。C++11起引入了std::regex库,支持模式匹配、搜索、替换等操作。下面通过几个常见实例说明如何使用。

1. 匹配邮箱地址

判断一个字符串是否为合法邮箱格式:

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string email = "test@example.com";
    std::regex pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");

    if (std::regex_match(email, pattern)) {
        std::cout << "邮箱格式正确\n";
    } else {
        std::cout << "邮箱格式错误\n";
    }
    return 0;
}

登录后复制

说明regex_match要求整个字符串完全匹配模式。R"(...)" 是原始字符串字面量,避免转义字符问题。

2. 查找字符串中的数字

从文本中找出所有连续的数字:

立即学习“C++免费学习笔记(深入)”;

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string text = "年龄:25,工号:10086,工资:15000";
    std::regex pattern(R"(\d+)");
    std::smatch matches;

    std::string::const_iterator start = text.begin();
    std::string::const_iterator end = text.end();

    while (std::regex_search(start, end, matches, pattern)) {
        std::cout << "找到数字: " << matches[0] << "\n";
        start = matches.suffix().first; // 移动到本次匹配结束位置
    }
    return 0;
}

登录后复制

说明regex_search用于在字符串中查找子串匹配,配合迭代可找出所有匹配项。matches[0]表示完整匹配结果。

标签: 正则表达式 ai c++ ios stream 邮箱

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~