C++标准库中正则表达式简介

                            

                                C++标准库中正则表达式的使用

                                                                                                  qianghaohao
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <regex>
using namespace std;

///
///               C++标准库中正则表达式的使用简介:
///   C++标准库中提供了对正表达式的支持,以下是常用的使用方法.
///
///   regex类:定义包含正则表达式的对象,如:regex rx("a(b?)c");
///
///   cmatch类:Type definition for char match_results.用来
///   定义保存匹配结果的对象-->typedef match_results<const char*> cmatch;
///   当待搜索的字符串是char类型是,使用此类对象
///
///   smatch类:Type definition for string match_results.用来
///   定义保存匹配结果的对象-->typedef match_results<string::const_iterator> smatch;
///   当待搜索的字符串是string类型是,使用此类对象
///   
///   ==========================以下是三个常用的正则匹配函数==================================
///   *bool regex_match(...)函数:Exactly matches a regular expression,判断是否准确匹配      *
///   *Tests whether a regular expression matches the entire target string                   *
///   *是否准确匹配整个目标字符串                                                            *
///   *注意:regex_match是目标字符串和正则表达式要完全匹配时才返回true.                       *
///   *如"abc"和"ab*c" 完全匹配,但是如果是"abcd"和"ab*c",虽然只有部分匹配(abc)但是返回是false*
///   *                                                                                      *
///   *bool regex_search(...)函数:Searches for a regular expression match.                   *
///   *在目标字符串中搜索一个匹配正则的字符串,如果搜索到了则返回true,否则返回false           *
///   *                                                                                      *
///   *regex_replace(...)函数:Replaces matched regular expressions.用指定的字符串替换匹      *
///   *配到的字符串,默认是替换所有目标字符串中匹配到的字符串,加了format_first_only标志       *
///   *表示只替换第一次匹配到的字符串                                                        *
///   ========================================================================================
///
///   ---->Regex Match Tracer 2.1:正则表达式匹配测试工具.
///
///

//#####---------->示例是对相关函数的多个重载形式的演示
///1.regex_match(...)使用示例:
#if 1
int main(int argc, char* argv[])
{

	// (1) with char*
	// Note how const char* requires cmatch and regex
	const char *first = "abc";  //待匹配字符串
	const char *last = first + strlen(first);
	cmatch narrowMatch;  //char *类型的对象来匹配保存结果
	regex rx("ab*c");  //定义包含正则表达式的对象

	//注意:regex_match是目标字符串和正则表达式要完全匹配时才返回true.
	// 如"abc"和"ab*c"完全匹配返回true,但是如果是"abcd"和"ab*c",虽然只有
	// 部分匹配(abc)但是返回是false
	//  regex_match有多个重载函数,可以只有三个参数,不保存结果.
	//  也可以有四个参数,第三个参数用来保存结果,一般情况下使用三个参数的就可以了
	bool found = regex_match(
		                      first,   //待匹配的开始位置
		                      last,  //待匹配的结束位置
		                      narrowMatch,  //保存结果
		                      rx    //正则表达式
		                    );  
	cout << found << endl;
	
	// (2) with std::string
	string target2("Drizzle");
	regex rx2("(D\\w+e)"); // no double backslashes with raw string literal
	found = regex_match(
		                 target2.cbegin(),  //匹配开始 -->迭代器区间开始开始位置
		                 target2.cend(),   //匹配结束 -->迭代器区间结束位置
		                 rx2   //正则表达式
		               );
	cout << found << endl;
	return 0;
}
#endif

///2.regex_search(...)使用示例/
///   示例是对regex_search(...)的多个重载形式的函数的使用
//
#if 1
int main()
{
	const char *first = "abcd";  //待搜索字符串
	const char *last = first + strlen(first);
	std::cmatch mr;  //保存匹配结果
	std::regex rx("abc");
	std::regex_constants::match_flag_type fl =  //regex_constants:一个名字空间
		std::regex_constants::match_default;

	std::cout << "search(f, f+1, \"abc\") == " << std::boolalpha  //bool类型以true或者false输出
		<< regex_search( first,  //目标字符串开始
			             first + 1,  //目标字符串结束
			             rx,  //正则表达式
			             fl  //匹配标志
			           ) << std::endl;

	
	std::cout << "search(f, l, \"abc\") == " << std::boolalpha
		<< regex_search( first,  //目标字符串开始
			             last,  //目标字符串结束
			             mr,  //将搜索结果存入mr
			             rx  //正则表达式
			           ) << std::endl;
	std::cout << "  matched: \"" << mr.str() << "\"" << std::endl;

	std::cout << "search(\"a\", \"abc\") == " << std::boolalpha
		<< regex_search( "a",  //待搜索字符串
			             rx   //正则表达式
			           ) << std::endl;

	std::cout << "search(\"xabcd\", \"abc\") == " << std::boolalpha
		<< regex_search( "xabcd",  //待搜索字符串
			             mr,  //将搜索结果存入mr
			             rx  //正则表达式
			           ) << std::endl;
	std::cout << "  matched: \"" << mr.str() << "\"" << std::endl;

	std::cout << "search(string, \"abc\") == " << std::boolalpha
		<< regex_search( std::string("a"),  //待搜索字符串,此参数为string类型
			             rx  //正则表达式
			           ) << std::endl;

	std::string str("abcabc");
	//std::match_results<std::string::const_iterator> mr2;
	smatch mr2;  //和上面等价 typedef定义的match_results<std::string::const_iterator>别名
	std::cout << "search(string, \"abc\") == " << std::boolalpha
		<< regex_search( str,  //待搜索字符串,此参数为string类型
			             mr2, //将搜索结果存入mr2
			             rx  //正则表达式
			           ) << std::endl;
	std::cout << "  matched: \"" << mr2.str() << "\"" << std::endl;

	return (0);
}
#endif

///3.regex_replace(...)使用示例/
#if 1
int main()
{
	char buf[20];
	const char *first = "axayaz";  //待匹配字符串
	const char *last = first + strlen(first);
	std::regex rx("a");  //正则表达式
	std::string fmt("A");
	std::regex_constants::match_flag_type fonly =
		std::regex_constants::format_first_only;

	//默认是替换所有目标字符串总匹配到的字符串,加了format_first_only标志
	//表示只替换第一次匹配到的字符串
	*std::regex_replace( &buf[0],  //被更改字符串的迭代器
		                 first,  //目标字符串开始位置
		                 last,  //目标字符串结束位置
		                 rx,  //正则表达式
		                 fmt  //要替换的字符串
		               ) = '\0';
	std::cout << "replacement == " << &buf[0] << std::endl;
	
	*std::regex_replace(&buf[0],  //被更改字符串的迭代器
		                first,  //目标字符串开始位置
		                last,  //目标字符串结束位置
		                rx,  //正则表达式
		                fmt,  //要替换的字符串
		                fonly  //替换标志,在此表示只替换第一次匹配到的字符串
		                ) = '\0';
	std::cout << "replacement == " << &buf[0] << std::endl;

	std::string str("adaeaf");
	std::cout << "replacement == "
		<< std::regex_replace( str,  //目标字符串
			                   rx,   //正则表达式
			                   fmt   //要替换的字符串
			                 ) << std::endl;

	std::cout << "replacement == "
		<< std::regex_replace(str,  //目标字符串
			                  rx,  //正则表达式
			                  fmt,  //要替换的字符串
			                  fonly  //替换标志,在此表示只替换第一次匹配到的字符串
			                 ) << std::endl;

	return (0);
}
#endif

///4.regex_search(...)循环遍历字符串示例/
///       --------->找到目标字符串中所有匹配的子串
///       ####----->此示例中找到s串中所有以subj开头的单词,并打印出来
/
#if 1
int main()
{
	std::string s("this subject has a subjmarine as a subjsequence subjmite");
	std::smatch m;
	std::regex e("\\b(subj)([^ ]*)");    // matches words beginning by "sub"  //GCC未支持

	std::cout << "目标序列: " << s << std::endl;
	std::cout << "正则公式: /\\b(sub)([^ ]*)/" << std::endl;
	std::cout << "The following matches and submatches were found:" << std::endl;

	while (std::regex_search(s, m, e)) {
		std::cout << m.str() << std::endl;  //输出匹配结果
		//std::cout << m[0] << std::endl;  //输出匹配结果,等价于上面那种用法
		s = m.suffix().str();  // 返回末端,作为新的搜索的开始
	}
	return 0;
}
#endif


 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值