C++正则表达式

需要引入库函数

#include<regex>

* 可以进行字符串的匹配
* 对于正则表达式出现的问题(正则表达式写错之类的),可以通过try、catch来捕捉异常
* 可以通过搜索,得到第一个匹配的子串或者通过迭代器,得到所有匹配的子串。

代码

#include<iostream>
#include<exception>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<iterator>
#include<list>
#include<deque>
#include<stack>
#include<queue>
#include<concurrent_priority_queue.h>
#include<algorithm>
#include<numeric>
#include<functional>  //bind
#include<map>
#include<set>
#include<unordered_map>
#include<memory>
#include<assert.h>
#include<tuple>
#include<regex>

using namespace std;

int main()
{
    cout << "start!" << endl;

    string pattern("[^c]ei");
    pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";

    regex r(pattern);
    smatch results;
    string test_str = "receipt freind theif receive";
    //输出第一个匹配的子串
    if (regex_search(test_str, results, r))
    {
        cout << results.str() << endl;
    }

    //输出所有匹配的子串
    for (sregex_iterator it(test_str.begin(), test_str.end(), r), end_it;
        it != end_it; ++it)
    {
        cout << it->str() << endl;
    }

    try
    {
        regex r("[[:alnum:]", regex::icase);
    }
    catch ( regex_error e )
    {
        cout << e.what() << endl << e.code() << endl;
    }

    cout << "end!" << endl;
    system("pause");
    return EXIT_SUCCESS;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C正则表达式是一种用于匹配、搜索和替换文本的工具。它可以通过一些特定的语法规则来描述一些文本模式,然后在文本中查找符合这些模式的内容。 在C标准库中的regex类可以用于实现正则表达式的功能。你可以使用regex类的成员函数来进行匹配、搜索和替换操作。 例如,你可以使用regex_match函数来判断一个字符串是否与指定的正则表达式匹配,使用regex_search函数来搜索文本中符合指定正则表达式的内容,使用regex_replace函数来替换文本中符合指定正则表达式的内容。 此外,你还可以使用一些特定的正则表达式语法来描述不同的文本模式,例如使用"."表示匹配任意字符,使用"*"表示匹配前面的字符零次或多次,使用"+"表示匹配前面的字符一次或多次,使用"[]"来表示匹配其中的任意一个字符,使用"{}"来表示匹配前面的字符一定次数等等。 使用C标准库中的regex类,你可以方便地进行正则表达式的操作,以满足你对文本匹配、搜索和替换的需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [C++ 正则表达式](https://blog.csdn.net/cat_fish_rain/article/details/130780540)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

littletomatodonkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值