C++正则表达式

前言

使用正则表达式可以方便我们对字符串的处理。C++中使用字符串首先需要包含头文件。一般使用正则表达式首先应该确定要匹配的模式,然后灵活运用regex_match,regex_search,regex_replace这三个函数。

1.正则表达式语法规则

详细的规则可以参考该网页,都有很详细的解释。正则表达式元字符

2.详细代码

#include <regex>
#include <iostream>
using namespace std;

int main()
{
	//regex_match
	regex pattern("[0-9]{1,3}.*");
	regex r(pattern);
	string str = "1wnieafnfao";
	bool status = regex_match(str, r);
	if (status == true) {
		printf("匹配成功!\n");
	}
	else {
		printf("匹配失败!\n");
	}
	/*结果:
		匹配成功
	*/
//********************************************************************
	//regex_search
	smatch result;
	string str1("i89love78you,mrsLu");
	bool sta = regex_search(str1, result, regex("[0-9]{2}[a-z]{1,4}[0-9]{2}"));
	for (auto it : result) {
		cout << it.str() << endl;
	}
	/*结果:
		89love78
	*/
	//注意括号区别,括号代表设定分组
	bool sta1 = regex_search(str1, result, regex("([0-9]{2})([a-z]{1,4})([0-9]{2})"));

	for (auto it : result) {
		cout << it.str() << endl;
	}
	/*结果:
		89love78
		89
		love
		78
	*/
	cout << result[0] << endl; //输出89love78
	cout << result.str(0) << endl; //输出89love78
	cout << result.str(1) << endl; //输出89
	cout << result.str(2) << endl; //输出love
	cout << result.str(3) << endl; //输出78
//********************************************************************
	//regex_replace
	regex pattern1("([0-9]{4})-([0-9]{2})-([0-9]{2})");
	regex r1(pattern1);
	string date = "日期为:2020-08-04 2020-05-30";
	//$代表选定第几组
	//$1:2020 $2:08 $3:04
	cout << regex_replace(date, r1, "$1.$2.$3") << endl;
    /*结果:
		日期为:2020.08.04 2020.05.30
	*/
	//********************************************************************
	//regex_iterator
	std::string s("this subject has a submarine as a subsequence");
	std::regex e("\\b(sub)([^ ]*)");   // matches words beginning by "sub",后跟非空白字符,遇到空格会终止

	std::regex_iterator<std::string::iterator> rit(s.begin(), s.end(), e);
	std::regex_iterator<std::string::iterator> rend;

	while (rit != rend) {
		std::cout << rit->str() << std::endl;
		++rit;
	}
	/*
	  输出为:
	  subject
	  submarine
	  subsequence
  */
	return 0;
}

代码来自:https://blog.csdn.net/A315776/article/details/107774791

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值