C++11 <regex>

/*
C++ 的正则表达式的库,初次感觉不是很好用,也许是个人还不太熟悉的原因吧!!!
主要是分三部分:
1 模式
2 容器
3 操作

1 模式:正则表达式的匹配就是“字符串模式”匹配,只不过正则表达式中有些字符是有特定的含义的,模式依据字符类型分成两类:
  std::regex: 针对 char* 和 string
  std::wregex: 针对 wchar_t* 和 wstring
2 容器:匹配总会有个结果,这些结果需要保存下来,依据字符表示方法和字符类型分成四类:
  std::cmatch: 针对 char*
  std::smatch: 针对 string
  std::wcmatch: 针对 wchar_t*
  std::wsmatch: 针对 wstring
3 操作 依据操作类型,分成三类:
 std::regex_match: 查找所有的匹配结果
 std::regex_serach:
 std::regex_replace:
*/

代码如下:

// regex_match example
#include <iostream>
#include <regex>
#include <string>

int main ()
{

    if (std::regex_match ("subject", std::regex("(sub)(.*)") ))
        std::cout << "string literal matched\n";

    const char cstr[] = "subject";
    std::string s ("subject");
    std::regex e ("(sub)(.*)");

    if (std::regex_match (s,e))
        std::cout << "string object matched\n";

    if ( std::regex_match ( s.begin(), s.end(), e ) )
        std::cout << "range matched\n";

    std::cmatch cm;    // same as std::match_results<const char*> cm;
    std::regex_match (cstr,cm,e);
    std::cout << "string literal with " << cm.size() << " matches\n";

    std::smatch sm;    // same as std::match_results<string::const_iterator> sm;
    std::regex_match (s,sm,e);
    std::cout << "string object with " << sm.size() << " matches\n";

    std::regex_match ( s.cbegin(), s.cend(), sm, e);
    std::cout << "range with " << sm.size() << " matches\n";

    // using explicit flags:
    std::regex_match ( cstr, cm, e, std::regex_constants::match_default );

    std::cout << "the matches were: ";
    for (unsigned i=0; i<sm.size(); ++i) {
        std::cout << "[" << sm[i] << "] ";
    }

    std::cout << std::endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值