首页 > 编程技术 > C语言

c++11中regex正则表达式示例简述

发布时间:2020-4-25 17:24

regex库中涉及到的主要类型有:

bool std::regex_match(...)
bool std::regex_search(...)
string std::regex_replace(...)//实际上返回类型是根据你输入的数据类型对应的basic_string类。

首先说明三个函数功能上的不同,std::regex_match是全文匹配,即它希望你输入的字符串要和正则表达式全部匹配,才认为匹配成功,否则匹配失败,而std::regex_search是在你输入的字符串中不断搜索符合正则表达式描述的子字符串,然后将第一个匹配到的子字符串返回。std::regex_replace是在std::regex_search的基础上更进一步,可以将匹配的子字符串替换为你提供的字符串。

看几个例子:

#include <iostream>
#include <string>
#include <regex>

int main() {
 std::regex pattern("\\d{4}");
 std::string content("hello_2018");
 std::smatch result;
 if (std::regex_match(content, result, pattern)) {
 std::cout << result[0];
 }
 system("pause");
 return 0;
}

匹配失败,什么都不会输出。

这里说明一下为什么输出的是result[0],其实result[0]返回的就是一个sub_match类型的对象。regex中认为正则表达式的每个括号对构成一个子匹配项,并认为整个字符串作为0号子匹配项,然后根据左括号出现的位置,从1号开始编号,因此返回的result[0]就是匹配整个正则表达式的字符串。

#include <iostream>
#include <string>
#include <regex>

int main() {
 std::regex pattern("\\d{4}");
 std::string content("hello_2018 by_2017");
 std::smatch result;
 if (std::regex_search(content, result, pattern)) {
 std::cout << result[0];
 }
 system("pause");
 return 0;
}

搜索到第一个符合正则表达式的子串,输出 2018。

#include <iostream>
#include <string>
#include <regex>

int main() {
 std::regex pattern("\\d{4}");
 std::string content("hello_2018 by_2017");
 std::smatch result;

 auto begin = content.cbegin();
 auto end = content.cend();
 while (std::regex_search(begin, end, result, pattern)) {
 std::cout << result[0] << " ";
 begin = result[0].second;
 }
 system("pause");
 return 0;
}

用上述方式可以输出字符串中所有符合正则表达式匹配要求的字符串,输出 2018 2017。

#include <iostream>
#include <string>
#include <regex>

int main() {
 std::regex pattern("\\d{4}");
 std::string content("hello_2018 by_2017");

 std::string result = std::regex_replace(content, pattern, "everyone");
 std::cout << result;
 system("pause");
 return 0;
}

输出 hello_everyone by_everyone。

以上就是c++11提供的regex模块的主要脉络,其余的关于对const char* 、wcahr_t类型的支持,以及regex_iterator、regex_token_iterator等迭代器的使用,以及掌控正则表达式行为方式的syntax_option_type的详细内容,等你需要去了解的时候去看官网的详解,相信学起来并不难。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对猪先飞的支持。

标签:[!--infotagslink--]

您可能感兴趣的文章: