[Boost基础]正则表达式库——regex

#include <iostream>
#include <string>
#include <conio.h>    
#include <boost/regex.hpp>
#include <locale>
//regex库
//正则表达式库boost.regex,正则表达式大大减轻了搜索特定模式字符串的负担,在大多数语言中都是强大的功能。Boost.Regex库中两个最重要的类是boost::regex和boost::smatch,它们都做boost/regex.hpp文件中定义。前者用于定义一个正则表达式,而后者可以保存搜索结果。

void test1()
{
	//std::locale::global(std::locale("German"));
	std::string s="Boris Schaling";
	boost::regex expr("\\w+\\s\\w+");
	std::cout<<boost::regex_match(s,expr)<<std::endl;//返回 1 用于字符串与正则表达式的比较
}  
void test2()
{
	std::locale::global((std::locale("German")));
	std::string s="Boris Schaling";
	boost::regex expr("(\\w+)\\s(\\w+)");
	boost::smatch what;
	if (boost::regex_search(s,what,expr))
	{
		std::cout<<what[0]<<"+++"<<what[1]<<"---"<<what[2]<<std::endl;
		//Boris Schaling+++Boris---Schaling
	}
	//函数regex_search()可以接受一个类型为smatch的引用的参数用于存储结果。函数regex_search()只是用于分类的搜索。
}  
void test3()
{
	std::locale::global(std::locale("German"));
	std::string s = " Boris Schaling ";
	boost::regex expr("\\s");
	std::string fmt("_");
	std::cout << boost::regex_replace(s, expr, fmt) << std::endl;// _Boris_Schaling_ 
	//除了待搜索的字符串和正则表达式之外,boost::regex_replace()函数还需要一个格式参数,它决定了子串、匹配正则表达式的分组如何被替换。如果正则表达式不包含任何分组,相关字串将用给定的格式一个个的被替换。
}  
void test4()
{
	std::locale::global(std::locale("German"));
	std::string s = "Boris Schaling";
	boost::regex expr("(\\w+)\\s(\\w+)");
	std::string fmt("\\2 \\1");
	std::cout << boost::regex_replace(s, expr, fmt) << std::endl;//Schaling Boris
	//格式参数可以访问有正则表达式分组的字串,这个例子正是使用了这项技术交换了姓、名的位置。
}
void test5()
{
	std::locale::global(std::locale("German"));
	std::string s = "Boris Schaling";
	boost::regex expr("(\\w+)\\s(\\w+)");
	std::string fmt("\\2 \\1");
	std::cout << boost::regex_replace(s, expr, fmt, boost::regex_constants::format_literal) << std::endl;//\2 \1
	//将boost::regex_constants::format_literal标志作为第4参数传递给函数boost::regex_replace(),从而抑制了格式参数中对特殊字符的处理。因为整个字符串匹配正则表达式,所以本例中经格式参数替换的到达的输出结果为 \2 \1
}
//C++的正则表达式库早已有之,但始终没有那个库纳入到标准化流程中。目前给看已经顺利的成为新一代C+标准库中的一员,结束了C++没有标准正则表达式支持的时代。
void test(char t)
{
	std::cout<<"press key====="<<t<<std::endl;
	switch (t)
	{ 
	case '1':test1();break;
	case '2':test2();break;
	case '3':test3();break;
	case '4':test4();break;
	case '5':test5();break; 
	case 27:
	case 'q':exit(0);break;
	default: std::cout<<"default "<<t<<std::endl;break;
	}
}
int main()
{
	while(1)
	{
		test(getch());
	} 
	return 0;
}

你可能感兴趣的:([Boost基础]正则表达式库——regex)