此文出处:http://www.msnfans.com/dumack/ 亲亲大麦壳
MSR GRETA 初探 MSR GRETA 是 Microsoft Research 的 Eric Niebler 开发的一个 free C++ 正则表达式实现,下载地址 http://research.microsoft.com/projects/greta/ 。大约是去年开始知道这个东西吧,但一直没有正式用他。今天开始使用,才发现他的文档是多么的简略;而网上其他地方关于greta的讨论几乎没有。俺猜,如此低的知名度,greta 会迟早就会被 ms drop。 不管如何,俺是决定用他了,于是就开始从源码下手。花了一个上午,终于对他的使用方法有点了解。 greta主要有如下类: rpattern 正则表达式类。 match_results 执行结果类 rpattern的主要方法:
- rpattern 构造函数。设置正则表达式和参数。
- match 执行正则表达式。可以接受三种参数:std::string, const char*, const_iterator。返回值为match_results::backref_type。
- subsitute 替换。只能接受 std::string。返回值为替换的数目。
- count 计算正则表达式在串中出现的次数。可以接受和 match 函数一样的三种参数。
- split 用正则表达式作为分隔符来切分串。也可以接受和 match 一样的三种参数。
- cgroups 计算正则表达式中包含的组数目。至少为1。
match_results的主要方法:这些方法都只有在调用过 rpattern::match 后才能使用。
- all_backref 返回 match_results 中的所有 backref 数组。包括组。如果在rpattern 中没有指定 GLOBAL | ALLBACKREFS 参数,则 all_backref 中最多只会包含 rpattern.cgroups() 个元素;若指定,会包含 rpattern.count() * rpattern.cgroups() 个元素。
- backref 返回 match_results 中指定位置的 backref。包括组。
- cbackrefs 返回 match_results 中 backref 个数。包括组。
rpatter 初始化时的参数说明:
- NOCASE 不区分大小写。
- GLOBAL 全局。如果指定该参数,rpattern::subsitute 会将串中全部匹配表达式的参数替换;否则(默认),若指定了 RIGHTMOST 参数,替换最后一个,没有指定(默认),替换第一个。
- MULTILINE 若不指定(默认),'^' 匹配串的开头,'$' 匹配串的结束;若指定,^ 匹配行开头,$ 匹配行结束。
- SINGLELINE 若不指定(默认),'.' 匹配除换行符(/n)外的任何字符;若指定,'.'也匹配换行符。SINGLELINE 看起来和 MULTILINE 不可一起用,其实她们的含义不是矛盾的,可以一起用。这是 GRETA 的 sb 之处,不知道是否从 perl copy过来的。
- RIGHTMOST 查找最右边的、最长的匹配串。默认是找左边的、最长的匹配串。btw, 在正则表达式中加 ? 可以使表达式找最短的匹配串。如串"test",re ".+" 会匹配整个 "test" 串,而 re ".+?" 则只匹配 "t"。
- NOBACKREFS 不记录 backref 。替换时用上此参数,可大幅度提高速度。这是文档上说的,俺没有试过。
- ALLBACKREFS 参见 match_results::all_backref 的解释。
上面说了 greta 的主要类。下面是如何使用 greta 。 使用 greta ,只要包含 regexpr2.h 这个头文件即可。 sample 1: 匹配 (from greta user's guide)。 match_results results; string str( "The book cost $12.34" ); rpattern pat( "//$(//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 ) { cout << "match success!" << endl; cout << "price: " << br << endl; } else { cout << "match failed!" << endl; } 结果为: match success! price: $12.34 sample 2: 包含组的匹配 match_results results; string str( "many mamy" ); rpattern pat("ma(.)y", GLOBAL | ALLBACKREFS); cout << "group count:/t" << pat.cgrous() << endl << endl; match_results::backref_type br = pat.match(str, results); if (br.matched) { cout << "match count:/t" << results.cbackrefs() << endl; dumack 发表于 14:33