GRETA如何使用正则表达式,获得多个匹配结果
match_results results;
string str( "The book cost $12.34 " );
rpattern pat( "cost \\$(\\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;
}
这是标准例子,如果str包含多个匹配结果,如何得到,显示出来
GRETA好象没有直接提供这样的功能,不过你可以自己通过使用字符串的偏移指针进行再次的匹配。
GRETA提供了
match_results::rstart和
match_results::rlength函数,前者返回匹配字符串在源字符串中的首位置,后一个函数(默认条件下)返回匹配字符串的长度,这两个函数在GRETA附带的帮助里都有说明。
你可以做一个循环,将指向源字符串的指针在每次匹配之后向后移动match_results::rstart+match_results::rlength个长度,让他从新的位置开始新的匹配,直到找不到匹配字符串为止……