一、作用
可用于字符串的匹配(Match)、查找(Search)、切割(Tokenize)、替换(replace)等工作。采用通配符(Wildcard)和模式(Pattern)作为关键字。
二、如何使用正则表达式库
1、引入头文件#include <regex>;
2、指定匹配模式std::regex;
3、调用正则函数std::regex_macth/search/replace(...);
三、示例
#include <regex>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
regex reg1{"<.*>.*</.*>"};
bool found = regex_match("<tag>Hello World!</tag>", reg1);
cout << "1 - found: " << found << endl;
regex reg2{ R"(<(.*)>.*</\1>)" }; // reg2与reg1等价
found = regex_match("<language>Hello C++!</language>", reg2);
cout << "2 - found: " << found << endl;
regex reg3(R"(<\(.*\)>.*</\1>)", regex_constants::grep);
found = regex_match("<tag>Hello regex</tag>", reg3);
cout << "3 - found: " << found << endl;
found = regex_match("<tag>Hello regex C_string</tag>", regex("<(.*)>.*</\\1>"));
cout << "4 - found: " << found << endl;
found = regex_match("XML tag: <tag>Hello XML</tag>", regex("<(.*)>.*</\\1>"));
cout << "5 - found: " << found << endl;
found = regex_match("XML tag: <tag>Hello XML</tag>", regex(".*<(.*)>.*</\\1>"));
cout << "6 - found: " << found << endl;
found = regex_search("XML tag: <tag>Hello XML</tag>", regex("<(.*)>.*</\\1>"));
cout << "7 - be search: " << found << endl;
return 0;
}
输出:
四、组(grouping)概念
正则模式设置可以采用组(grouping)的概念;
采用(...)表示捕获组,使用\n引用该组,n表示第n组
eg:R"(<(.*)>.*</\1>)",(.*)为捕获组,\1引用(.*)。
五、regex_match与regex_search
regex_match:整个字符串匹配正则表达式;
regex_search:部分字符串匹配正则表达式。