您的位置:首页 > 其它

Greta 入门指南

2016-05-31 13:32 211 查看
GRETA是微软研究院推出的一个正则表达式模板类库,GRETA 包含的 C++ 对象和函数,使字符串的模式匹配和替换变得很容易,它们是:

rpattern: 搜索的模式

match_results/subst_results: 放置匹配、替换结果的容器

为了执行搜索和替换的操作,用户首先需要用一个描述匹配规则的字符串来显式初始化一个rpattern对象,然后把需要匹配的字符串作为参数,调用rpattern的函数,比如match()或者substitute(),就可以得到匹配后的结果。如果match()/substitute()调用失败,函数返回false,如果调用成功,函数返回true,此时,match_results对象存储了匹配结果。请看例子代码:

#include <iostream>
#include <string>
#include "regexpr2.h"

#ifdef _UNICODE
#define tstring wstring
#define tcout   wcout
#else
#define tstring string
#define tcout   cout
#endif

using namespace std;
using namespace regex;

int main()
{
match_results results;
tstring str( _T("The book cost $12.34") );
rpattern pat( _T("\\$(\\d+)(\\.(\\d\\d))?") );
// Match a dollar sign followed by one or more digits,
// optionally followed by a period and two more digits.
// The double-escapes are necessary to satisfy the compiler.

match_results::backref_type br = pat.match( str, results );
if( br.matched )
{
tcout << ("match success!") << endl;
tcout << ("price: ") << br << endl;
}
else
{
tcout << ("match failed!") << endl;
}
return 0;
}

程序输出结果:

match success!
price: $12.34
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: