正则表达式与C++11(m[].str()待修改)

1. 表达式语法

参考网站:

http://regexr.com/

http://www.regexpal.com/

:heart:regex101:heart:

2. C++11 Regex基本API

​ **注:**以下函数声明并非官方原型,仅是为了方便理解使用而产生形式。详细可以查询 cppreference.com

  • 引用头文件#include <regex>

  • std::regex

    • s: 字符串形式的正则表达式
    1
    2
    // 初始化一个std::regex对象作为匹配模板	
    std::regex(std::string s);
  • std::regex_match

    • src: 待匹配字符串
    • m: 传出参数包含了匹配的结果信息,匹配的字符串也会保存在这里, 注意std::match_result作为基类,实际使用的时候需要调用子类std::cmatch或者std::smatch, 代表结果的储存是char*或者std::string::const_iterator
    • r: 上文构建的std::regex对象
    1
    2
    3
    // 将匹配结果放在m中
    // 返回值代表匹配是否成功
    bool std::regex_match(std::string src, std::match_result m, std::regex r);
  • std::regex_search

    1
    bool std::regex_match(std::string src, std::match_result m, std::regex r);
  • std::regex_iterator

3. 注解

Because regex_match only considers full matches, the same regex may give different matches between regex_match and std::regex_search:

1
2
3
4
5
6
std::regex re("Get|GetValue");
std::cmatch m;
std::regex_search("GetValue", m, re); // returns true, and m[0] contains "Get"
std::regex_match ("GetValue", m, re); // returns true, and m[0] contains "GetValue"
std::regex_search("GetValues", m, re); // returns true, and m[0] contains "Get"
std::regex_match ("GetValues", m, re); // returns false

regex_search 会在字符串中查找与正则表达式模式匹配的子串,而 regex_match 则要求整个被匹配字符串都与正则表达式模式匹配。另外regex_search只成功匹配一次就会返回,意味着得到所有匹配的结果需要迭代查找。

  • 如何使用匹配结果?