微软 Greta 正则表达式库。

正则表达式的强大功能让不少程序员垂涎三尺,不少程序设计语言都有正则表达式库,C++ 呢?当然也有。

Greta 库是微软研究院推出的一个正则表达式模板类库,Greta 包含的 C++ 对象和函数,使字符串的模式匹配和替换变得很容易。也许现在最流行的不是 Greta,但不同的正则表达式匹配引擎擅长于不同匹配模式。作为一个基准,当用模式:"^([0-9]+)(\-| |$)(.*)$" 匹配字符串 "100- this is a line of ftp response which contains a message string" 时,Greta 的匹配速度比 boost(http://www.boost.org)正则表达式库大约快7倍,比 ATL7 的 CATLRegExp 快 10 倍之多!Boost Regex 的说明文档带有一个很多模式的匹配测试Performance结果。比较这个结果后,Greta 在大部分情况下和 Boost Regex 性能差不多,但是在用 Visual Studio.Net 2003 编译的情况下,Greta 还略胜一筹。

就算不使用Greta库,也可以学习下Greta的代码,提高自己的编程水平。

先放出下载地址:

http://cid-c12002e5d442fe85.skydrive.live.com/

在Common Code中找到Greta 2.6.4.rar。

下载后使用VC建立一个静态库项目,然后把里面的6个源文件都添加进去,编译即可获得Greta.lib。

使用方法:

例:

新建一个应用程序项目,这里以控制台程序 GretaTester 为例。环境为MciroSoft Windows XP SP3 Professional + MicroSoft Visual Studio 2008 Team System。

然后把Greta库中的4个头文件syntax2.h,restack.h,regexpr2.h,reimpl2.h,还有Greta.lib复制到项目目录下。

还有最重要的一步,否则你是100%出现无数错误提示的

VC下,菜单“项目|XXXX属性|配置属性|C/C++|预处理器”

把“预处理器定义”改为 WIN32;_DEBUG;_LIB;_SCL_SECURE_NO_WARNINGS

以下为调用代码:

// GretaTester.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include "regexpr2.h"
using namespace std;
using namespace regex;
#pragma comment(lib, "Greta.lib")
#ifndef _tstring
    #ifndef UNICODE
        #define _tstring string
    #else
        #define _tstring wstring
    #endif
#endif
#ifndef _tcout
    #ifndef UNICODE
        #define _tcout cout
    #else
        #define _tcout wcout
    #endif
#endif
#ifndef _tcin
    #ifndef UNICODE
        #define _tcin cin
    #else
        #define _tcin wcin
    #endif
#endif
int _tmain(int argc, _TCHAR* argv[])
{
    match_results results;
    _tstring str;
    _tcin >> str;
    rpattern pat(_T("[a-zA-Z]{1,}"));
    match_results::backref_type br = pat.match(str, results);
    if (br.matched)
    {
        _tcout << _T("Match Successed!") << endl;
        _tcout << _T("The Matched String is: ") << br << endl;
    }
    else
    {
        _tcout << _T("Match Failed!") << endl;
    }
    return 0;
}

运行以上程序,输入字符串“123abc123”,看结果是什么?