【BOOST程序库】正则表达式相关操作

基本概念这里不解释了,代码中详细解释了BOOST程序库中对于正则表达式常用方法的详细用法。

#include <iostream>
#include <string>

//正则表达式头文件
#include <boost/xpressive/xpressive.hpp>

int main() {
	//声明正则:boost::pressive::cregex
	boost::xpressive::cregex reg = boost::xpressive::cregex::compile("a.c");
	//匹配正则:boost::pressive::cregex_match
	if (boost::xpressive::regex_match("abc", reg)) {
		std::cout << "匹配成功" << std::endl;
	}
	else {
		std::cout << "匹配失败!" << std::endl;
	}
	if (boost::xpressive::regex_match("a=c", reg)) {
		std::cout << "匹配成功" << std::endl;
	}
	else {
		std::cout << "匹配失败!" << std::endl;
	}
	if (boost::xpressive::regex_match("a+c", reg)) {
		std::cout << "匹配成功" << std::endl;
	}
	else {
		std::cout << "匹配失败!" << std::endl;
	}

	//字符串正则:
	//声明正则:622421197706251568
	//R"(d{6}(1|2)d{3}(0|1)d[0-3]dd{3}(X|d))"
	boost::xpressive::cregex reg1 = boost::xpressive::cregex::compile(R"(622421(1|2)d{3}(0|1)[1-9][1-3][0-9]d{3}(d|X))");
	std::cout << boost::xpressive::regex_match("62242119770611231X", reg1) << std::endl;
	std::cout << boost::xpressive::regex_match("622421200506111765", reg1) << std::endl;
	std::cout << boost::xpressive::regex_match("622421162506311564", reg1) << std::endl;
	std::cout << boost::xpressive::regex_match("62242115960621231X", reg1) << std::endl;
	std::cout << boost::xpressive::regex_match("622421200412452156", reg1) << std::endl;

	boost::xpressive::cregex reg3 = boost::xpressive::cregex::compile("string-(.{4})");
	char Str[] = "this is a string-xxxx";
	boost::xpressive::cmatch what;
	boost::xpressive::regex_search(Str, what, reg3);

	//正则表达式,匹配成功后替换:
	std::string Str1 = "readmereadme.txt";
	boost::xpressive::sregex regg1 = boost::xpressive::sregex::compile("(.*)(me)");
	boost::xpressive::sregex regg2 = boost::xpressive::sregex::compile("(t)(.)(t)");

	//替换:$1代表找到的m的位置
	std::cout << boost::xpressive::regex_replace(Str1, regg1, "$1ing") << std::endl;  //readmereading.txt
	std::cout << boost::xpressive::regex_replace(Str1, regg1, "ing") << std::endl;    //ing.txt
	std::cout << boost::xpressive::regex_replace(Str1, regg1, "$1L$2") << std::endl;  //readmereadLme.txt
	std::cout << boost::xpressive::regex_replace(Str1, regg2, "$1L$3") << std::endl;  //readmereadme.tLt
	//替换文件名:
	std::cout << boost::xpressive::regex_replace(Str1, regg2, "$1exe") << std::endl;  //readmereadme.texe

	std::cout << boost::xpressive::regex_replace(Str1, regg2, "$1L$2") << std::endl;  //readmereadme.tLx


	system("pause");
	return 0;
}