温馨提示×

c++ string匹配如何支持正则表达式

c++
小樊
81
2024-09-25 07:35:14
栏目: 编程语言

C++的<regex>库支持正则表达式。你可以使用std::regex类来创建一个正则表达式对象,然后使用它的成员函数来执行匹配操作。

下面是一个简单的示例,演示如何使用C++的<regex>库进行正则表达式匹配:

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

int main() {
    std::string str = "Hello, my email is example@example.com and my phone number is 123-456-7890";
    
    // 创建一个正则表达式对象,匹配邮箱地址
    std::regex email_regex(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b)");
    
    // 在字符串中查找所有匹配的邮箱地址
    std::smatch matches;
    std::string::const_iterator searchStart(str.cbegin());
    while (std::regex_search(searchStart, str.cend(), matches, email_regex)) {
        std::cout << "Found email: " << matches[0] << std::endl;
        searchStart = matches.suffix().first;
    }
    
    // 创建一个正则表达式对象,匹配电话号码
    std::regex phone_regex(R"(\d{3}-\d{3}-\d{4})");
    
    // 在字符串中查找所有匹配的电话号码
    searchStart = str.cbegin();
    while (std::regex_search(searchStart, str.cend(), matches, phone_regex)) {
        std::cout << "Found phone number: " << matches[0] << std::endl;
        searchStart = matches.suffix().first;
    }
    
    return 0;
}

在上面的示例中,我们创建了两个正则表达式对象:email_regex用于匹配邮箱地址,phone_regex用于匹配电话号码。然后,我们使用std::regex_search函数在字符串str中查找所有匹配的邮箱地址和电话号码,并将它们打印出来。

注意,正则表达式中的特殊字符需要进行转义。例如,在上面的示例中,我们在正则表达式中使用了\b来表示单词边界,使用了\.来表示点字符。这是因为这些字符在正则表达式中具有特殊的含义。

0