首页 > 编程语言 > 详细

C++正则表达式笔记

时间:2019-02-17 00:35:07      阅读:338      评论:0      收藏:0      [点我收藏+]

C++11中引入了正则表达式库

常用的3个接口:

1.regex_match,完全匹配

示例1:

#include <iostream>
#include <regex>
int main()
{
    std::string text = "long long ago";
    std::string text2 = "long long";
    std::regex re(".+ng");
    std::cout << std::boolalpha << std::regex_match(text, re) << std::endl;  //false
    std::cout << std::regex_match(text2, re) << std::endl;  //true
    std::system("pause");
    return 0;
}

示例1中匹配模式为.+ng,因为采用完全匹配,所以仅当目标文本以ng结尾才返回true

2.regex_search,在目标文本中进行搜索

示例2:

#include <iostream>
#include <regex>
int main()
{
    using namespace std;
    string text = "I‘m 25.";
    string text2 = "I am 25 years old.";
    regex re("[0-9]+");
    smatch sm;
    if (regex_search(text, sm, re))
    {
        cout << sm[0] << endl;
    }
    if (regex_search(text2, sm, re))
    {
        cout << sm[0] << endl;
    }
    system("pause");
    return 0;
}

3.sregex_iterator,用于遍历所有匹配

示例3:

#include <iostream>
#include <string>
#include <regex>
int main()
{
    using namespace std;
    string text = "I‘m 25. And my friend Bush is 24 years old.";
    regex re("[0-9]+");
    sregex_iterator itr1(text.begin(), text.end(), re);
    sregex_iterator itr2;
    for (sregex_iterator itr = itr1; itr != itr2; ++itr)
    {
        smatch sm = *itr;
        cout << sm[0].str() << endl;
    }
    system("pause");
    return 0;
}

 

C++正则表达式笔记

原文:https://www.cnblogs.com/buyishi/p/10385094.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!